CoreJava Imp Point
CoreJava Imp Point
Disclaimers
No claims are made about the accuracy of this document and no responsibility is taken
for any errors. The exam objectives below are quoted, as is from Sun Microsystems
web site. This document can be used and distributed as long as the purpose is not
commercial.
This document has material collected from a lot of resources. Some resources are listed
here.
1.
2.
3.
4.
Java 1.1 Certification Study Guide by Simon Roberts and Philip Heller.
Java 2 Certification Study Guide by Simon Roberts, Philip Heller and Michael Ernst.
Java 2 Exam Cram by Bill Brogden
A Programmers guide to Java Certification by Khalid Azim Mughal and Rolf
Rasmussen
5. Java
Language
Specification
from
Sun
http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html
6. Java tutorial from Sun - http://java.sun.com/docs/books/tutorial/index.html
7. Java API documentation from Sun - http://java.sun.com/j2se/1.3/docs/api/overviewsummary.html
8. Marcus Green - http://www.jchq.net
9. Java Ranch Discussions and Archives - http://www.javaranch.com/
10. Maha Annas Resource Page - http://www.javaranch.com/maha/
11. Jyothi's page - http://www.geocities.com/SiliconValley/Network/3693/
12. Dylan Walshs exam revision page - http://indigo.ie/~dywalsh/certification/index.htm
13. Rose India Web Site
14. And an ever-increasing list of web sites regarding SCJP certification.
If you find any error or have some opinion or wanna share feedback, please e-mail
rajeevkumar.mohan@gmail.com
Please mention your opinion and let this document cover more topics , you can edit ,
add more material and can back to me so , I can distribute it further to you people .
You can never cast objects of sibling classes( sharing the same parent ), even with an
explicit cast.
.equals returns false if the object types are different.It does not raise a compiler error.
No inner class can have a static member.
File class has NO methods to deal with the contents of the file.
InputStream and OutputStream are abstract classes, while DataInput and DataOutput
are interfaces.
Size
(bits)
1
8
16
16
32
64
32
64
Initial
Value
false
0
0
\u0000
0
0L
0.0F
0.0
Min Value
Max Value
false
-128 (-27)
-215
\u0000 (0)
-231
-263
1.4E-45
4.9E-324
True
127 (27 1)
215 1
\uFFFF (216 1)
231 1
263 1
3.4028235E38
1.7976931348623157E308
13. All numeric data types are signed. char is the only unsigned integral type.
14. Object reference variables are initialized to null.
15. Octal literals begin with zero. Hex literals begin with 0X or 0x.
16. Char literals are single quoted characters or unicode values (begin with \u).
17. A number is by default an int literal, a decimal number is by default a double literal.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 8 of 109
.
Color
Red
Green
Blue
Yellow
Type of Operators
Postfix operators
Prefix Unary operators
Object creation and cast
Multiplication/Division/Modu
lus
Addition/Subtraction
Shift
Relational
Equality
Bit-wise/Boolean AND
Bit-wise/Boolean XOR
Bit-wise/Boolean OR
Logical AND (Short-circuit or
Conditional)
Logical OR (Short-circuit or
Conditional)
Ternary
Assignment
Operators [Presidence]
[] . (parameters) ++ -++ -- + - ~ !
new (type)
*/%
Associativity
Left to Right
Right to Left
Right to Left
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
Left to Right
||
Left to Right
?:
Right to Left
= += -= *= /= %= <<= >>= >>>= &= Right to Left
^= |=
Sub-classes
3. final
final features cannot be changed.
final classes cannot be sub-classed.
final variables cannot be changed. (Either a value has to be specified at
declaration or an assignment statement can appear only once).
final methods cannot be overridden.
Method arguments marked final are read-only. Compiler error, if trying to assign
values to final arguments inside the method.
Member variables marked final are not initialized by default. They have to be
explicitly assigned a value at declaration or in an initializer block. Static finals
must be assigned to a value in a static initializer block, instance finals must be
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 18 of 109
.
//
This
will
invoke
will
invoke
p = c;
p.doStuff();
//
This
will
invoke
Parent.doStuff(), rather than Child.doStuff()
}
}
class Parent {
static int x = 100;
public static void doStuff() {
System.out.println("In Parent..doStuff");
System.out.println(x);
}
}
class Child extends Parent {
static int x = 200;
public static void doStuff() {
System.out.println("In Child..doStuff");
System.out.println(x);
}
}
6. native
Can be applied to methods only. (static methods also)
Written in a non-Java language, compiled for a single machine target type.
Java classes use lot of native methods for performance and for accessing hardware
Java is not aware of.
Native method signature should be terminated by a ;, curly braces will provide a
compiler error.
native doesnt affect access qualifiers. Native methods can be private.
Can pass/return Java objects from native methods.
System.loadLibrary is used in static initializer code to load native libraries. If the
library is not loaded when the static method is called, an UnsatisfiedLinkError is
thrown.
7. transient
Can be applied to class level variables only.(Local variables cannot be declared
transient)
Transient variables may not be final or static.(But compiler allows the declaration,
since it doesnt do any harm. Variables marked transient are never serialized.
Static variables are not serialized anyway.)
Not stored as part of objects persistent state, i.e. not written out during
serialization.
Can be used for security.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 20 of 109
.
Cla
ss
Inner classes
(Except local
and
anonymous
classes)
Y
Y
Y (OK for all)
Varia
ble
Metho Constructor
d
Free floating
Code block
public
protected
No access
modifier
private
final
Y
N
Y
Y
Y
Y
Y
Y
Y
Y
Y
Y
N
N
N
Y
Y
Y
Y
Y
N
N
N
Y
Y
(Except
anonymous
classes)
Y
(Except
anonymous
classes)
Y
abstract
static
native
transient
synchroniz
ed
N
N
N
N
N
N
N
Y
N
Y
N
Y
N
N
N
volatile
Y
(static
initializer)
N
N
Y (part of
method, also
need
to
specify
an
object
on
which a lock
should
be
obtained)
N
N
Y
char
Casting of Primitives
9. Needed with narrowing conversions. Use with care radical information loss. Also
can be used with widening conversions, to improve the clarity of the code.
10. Can cast any non-boolean type to another non-boolean type.
11. Cannot cast a boolean or to a boolean type.
Conversion of Object references
12. Three types of reference variables to denote objects - class, interface or array type.
13. Two kinds of objects can be created class or array.
14. Two types of conversion assignment and method call.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 23 of 109
.
Compile-time Rules
When old and new types are classes, one class must be the sub-class of the
other.
When old and new types are arrays, both must contain reference types and it
must be legal to cast between those types (primitive arrays cannot be cast,
conversion possible only between same type of primitive arrays).
We can always cast between an interface and a non-final object.
Run-time rules
If new type is a class, the class of the expression being converted must be new
type or extend new type.
If new type is an interface, the class of the expression being converted must
implement the interface.
An Object reference can be converted to: (java.lang.Object)
an Object reference
a Cloneable interface reference, with casting, with runtime check
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 24 of 109
.
1. Loop constructs
3 constructs for, while, do
All loops are controlled by a boolean expression.
In while and for, the test occurs at the top, so if the test fails at the first time, body
of the loop might not be executed at all.
In do, test occurs at the bottom, so the body is executed at least once.
In for, we can declare multiple variables in the first part of the loop separated by
commas, also we can have multiple statements in the third part separated by
commas.
In the first section of for statement, we can have a list of declaration statements or
a list of expression statements, but not both. We cannot mix them.
All expressions in the third section of for statement will always execute, even if
the first expression makes the loop condition false. There is no short circuit here.
2. Selection Statements
if takes a boolean arguments. Parenthesis required. else part is optional. else if
structure provides multiple selective branching.
switch takes an argument of byte, short, char or int.(assignment compatible to int)
case value should be a constant expression that can be evaluated at compile time.
Compiler checks each case value against the range of the switch expressions data
type. The following code wont compile.
byte b;
switch (b) {
case 200: // 200 not in range of byte
default:
}
We need to place a break statement in each case block to prevent the execution to
fall through other case blocks. But this is not a part of switch statement and not
enforced by the compiler.
We can have multiple case statements execute the same code. Just list them one
by one.
default case can be placed anywhere. Itll be executed only if none of the case
values match.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 26 of 109
.
switch can be nested. Nested case labels are independent, dont clash with outer
case labels.
Empty switch construct is a valid construct. But any statement within the switch
block should come under a case label or the default case label.
3. Branching statements
break statement can be used with any kind of loop or a switch statement or just a
labeled block.
continue statement can be used with only a loop (any kind of loop).
Loops can have labels. We can use break and continue statements to branch out of
multiple levels of nested loops using labels.
Names of the labels follow the same rules as the name of the
variables.(Identifiers)
Labels can have the same name, as long as they dont enclose one another.
There is no restriction against using the same identifier as a label and as the name
of a package, class, interface, method, field, parameter, or local variable.
4. Exception Handling
An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
There are 3 main advantages for exceptions:
1. Separates error handling code from regular code
2. Propagating errors up the call stack (without tedious programming)
3. Grouping error types and error differentiation
An exception causes a jump to the end of try block. If the exception occurred in a
method called from a try block, the called method is abandoned.
If theres a catch block for the occurred exception or a parent class of the
exception, the exception is now considered handled.
At least one catch block or one finally block must accompany a try
statement. If all 3 blocks are present, the order is important. (try/catch/finally)
finally and catch can come only with try, they cannot appear on their own.
Regardless of whether or not an exception occurred or whether or not it was
handled, if there is a finally block, itll be executed always. (Even if there is a
return statement in try block).
System.exit() and error conditions are the only exceptions where finally block is
not executed.
If there was no exception or the exception was handled, execution continues at the
statement after the try/catch/finally blocks.
If the exception is not handled, the process repeats looking for next enclosing try
block up the call hierarchy. If this search reaches the top level of the hierarchy
(the point at which the thread was created), then the thread is killed and message
stack trace is dumped to System.err.
Use throw new xxxException() to throw an exception. If the thrown object is null,
a NullPointerException will be thrown at the handler.
If an exception handler re-throws an exception (throw in a catch block), same
rules apply. Either you need to have a try/catch within the catch or specify the
entire method as throwing the exception thats being re-thrown in the catch block.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 27 of 109
.
Catch blocks at the same level will not handle the exceptions thrown in a catch
block it needs its own handlers.
The method fillInStackTrace() in Throwable class throws a Throwable object. It
will be useful when re-throwing an exception or error.
The Java language requires that methods either catch or specify all checked
exceptions that can be thrown within the scope of that method.
All objects of type java.lang.Exception are checked exceptions. (Except the
classes under java.lang.RuntimeException) If any method that contains lines of
code that might throw checked exceptions, compiler checks whether youve
handled the exceptions or youve declared the methods as throwing the
exceptions. Hence the name checked exceptions.
If theres no code in try block that may throw exceptions specified in the catch
blocks, compiler will produce an error. (This is not the case for super-class
Exception)
Java.lang.RuntimeException and java.lang.Error need not be handled or declared.
An overriding method may not throw a checked exception unless the overridden
method also throws that exception or a super-class of that exception. In other
words, an overriding method may not throw checked exceptions that are not
thrown by the overridden method. If we allow the overriding methods in subclasses to throw more general exceptions than the overridden method in the parent
class, then the compiler has no way of checking the exceptions the sub-class
might throw. (If we declared a parent class variable and at runtime it refers to subclass object) This violates the concept of checked exceptions and the sub-classes
would be able to by-pass the enforced checks done by the compiler for checked
exceptions. This should not be allowed.
Overloading
Overriding
Signature has to be different. Just a Signature has to be the same. (including the
difference in return type is not enough.
return type)
Accessibility may vary freely.
Overriding methods cannot be more private
than the overridden methods.
Exception list may vary freely.
Overriding methods may not throw more
checked exceptions than the overridden
methods.
Just the name is reused. Methods are Related directly to sub-classing. Overrides
independent methods. Resolved at the parent class method. Resolved at runcompile-time based on method signature. time based on type of the object.
Can call each other by providing Overriding method can call overridden
appropriate argument list.
method by super.methodName(), this can be
used only to access the immediate superclasss method. super.super wont work.
Also, a class outside the inheritance
hierarchy cant use this technique.
Methods can be static or non-static. Since static methods dont participate in overriding,
the methods are independent, it doesnt since they are resolved at compile time based
matter. But if two methods have the same on the type of reference variable. A static
signature, declaring one as static and method in a sub-class cant use super (for
another as non-static does not provide a the same reason that it cant use this for)
valid overload. Its a compile time error.
Remember that a static method cant be
overridden to be non-static and a non-static
method cant be overridden to be static. In
other words, a static method and a non-static
method cannot have the same name and
signature (if signatures are different, it would
have formed a valid overload)
Theres no limit on number of overloaded Each parent class method may be overridden
methods a class can have.
at most once in any sub-class. (That is, you
cannot have two identical methods in the
same class)
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 30 of 109
.
}
In the above code, if we didnt have the overriding getS() method in the sub-class
and if we call the method from sub-class reference variable, the method will
return only the super-class member variable value. For explanation, see the
following point.
Also, methods access variables only in context of the class of the object they
belong to. If a sub-class method calls explicitly a super class method, the
super class method always will access the super-class variable. Super class
methods will not access the shadowing variables declared in subclasses
because they dont know about them. (When an object is created, instances of
all its super-classes are also created.) But the method accessed will be again
subject to dynamic lookup. It is always decided at runtime which
implementation is called. (Only static methods are resolved at compile-time)
public class Shadow2 {
String s = "main";
public static void main(String s[]) {
S2 s2 = new S2();
s2.display(); // Produces an output S1, S2
S1 s1 = new S1();
System.out.println(s1.getS()); // prints S1
System.out.println(s2.getS()); // prints S1 since
super-class method
// always accesses super-class
variable
}
}
class S1 {
String s = "S1";
public String getS() {
return s;
}
void display() {
System.out.println(s);
}
}
class S2 extends S1{
String s = "S2";
void display() {
super.display();
// Prints S1
System.out.println(s); // prints S2
}
}
With OO languages, the class of the object may not be known at compile-time
(by virtue of inheritance). JVM from the start is designed to support OO. So,
the JVM insures that the method called will be from the real class of the
object (not with the variable type declared). This is accomplished by virtual
method invocation (late binding). Compiler will form the argument list and
produce one method invocation instruction its job is over. The job of
identifying and calling the proper target code is performed by JVM.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 32 of 109
.
JVM knows about the variables real type at any time since when it allocates
memory for an object, it also marks the type with it. Objects always know
who they are. This is the basis of instanceof operator.
Sub-classes can use super keyword to access the shadowed variables in superclasses. This technique allows for accessing only the immediate super-class.
super.super is not valid. But casting the this reference to classes up above
the hierarchy will do the trick. By this way, variables in super-classes above
any level can be accessed from a sub-class, since variables are resolved at
compile time, when we cast the this reference to a super-super-class, the
compiler binds the super-super-class variable. But this technique is not
possible with methods since methods are resolved always at runtime, and the
method gets called depends on the type of object, not the type of reference
variable. So it is not at all possible to access a method in a super-super-class
from a subclass.
public class ShadowTest {
public static void main(String s[]){
new STChild().demo();
}
}
class STGrandParent {
double wealth = 50000.00;
public double getWealth() {
System.out.println("GrandParent-"
+
wealth);
return wealth;
}
}
class STParent extends STGrandParent {
double wealth = 100000.00;
public double getWealth() {
System.out.println("Parent-" + wealth);
return wealth;
}
}
class STChild extends STParent {
double wealth = 200000.00;
public double getWealth() {
System.out.println("Child-" + wealth);
return wealth;
}
public void demo() {
getWealth(); // Calls Child method
super.getWealth();
//
Calls
Parent
method
// Compiler error, GrandParent method
cannot be accessed
//super.super.getWealth();
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 33 of 109
.
Private methods are not overridden, so calls to private methods are resolved at
compile time and not subject to dynamic method lookup. See the following
example.
public class Poly {
public static void main(String args[]) {
PolyA ref1 = new PolyC();
PolyB ref2 = (PolyB)ref1;
System.out.println(ref2.g()); // This prints 1
// If f() is not private in PolyB, then prints 2
}
}
class PolyA {
private int f() { return 0; }
public int g() { return 3; }
}
class PolyB extends PolyA {
private int f() { return 1; }
public int g() { return f(); }
}
class PolyC extends PolyB {
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 35 of 109
.
Interfaces
All methods in an interface are implicitly public, abstract, and never static.
All variables in an interface are implicitly static, public, final. They cannot be
transient or volatile. A class can shadow the variables it inherits from an
interface, with its own variables.
A top-level interface itself cannot be declared as static or final since it doesnt
make sense.
Declaring parameters to be final is at methods discretion, this is not part of
method signature.
Same case with final, synchronized, native. Classes can declare the methods to
be final, synchronized or native whereas in an interface they cannot be
specified like that. (These are implementation details, interface need not worry
about this)
But classes cannot implement an interface method with a static method.
If an interface specifies an exception list for a method, then the class
implementing the interface need not declare the method with the exception
list. (Overriding methods can specify sub-set of overridden methods
exceptions, here none is a sub-set). But if the interface didnt specify any
exception list for a method, then the class cannot throw any exceptions.
All interface methods should have public accessibility when implemented in
class.
Interfaces cannot be declared final, since they are implicitly abstract.
A class can implement two interfaces that have a method with the same
signature or variables with the same name.
Inner Classes
A class can be declared in any scope. Classes defined inside of other classes
are known as nested classes. There are four categories of nested classes.
1. Top-level nested classes / interfaces
Declared as a class member with static modifier.
Just like other static features of a class. Can be accessed / instantiated
without an instance of the outer class. Can access only static members of
outer class. Cant access instance variables or methods.
Very much like any-other package level class / interface. Provide an
extension to packaging by the modified naming scheme at the top level.
Classes can declare both static and non-static members.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 37 of 109
.
//
Prints
"Sharmi",
ic
new
OuterClass().new
Entity
Declaration
Context
Accessibilit
y Modifiers
Package level
class
Top
level
nested class
(static)
Non
static
inner class
As package Public
member
default
As static class All
member
As non-static All
class member
Outer
instanc
e
or No
No
Yes
Local
class In block with None
(non-static)
non-static
context
Yes
Local
(static)
No
Anonymous
In block with None
class
(non- non-static
static)
context
Yes
Anonymous
class (static)
No
Top
level As static class All
nested
member
interface
(static)
or No
No
Direct Access
to
enclosing
context
N/A
Defines static or
non-static
members
Both static and
non-static
Static members Both static and
in
enclosing non-static
context
All members in Only non-static
enclosing
context
All members in Only non-static
enclosing
context + local
final variables
Static members Only non-static
in
enclosing
context + local
final variables
All members in Only non-static
enclosing
context + local
final variables
Static members Only non-static
in
enclosing
context + local
final variables
N/A
Static variables
and
non-static
method
prototypes
Static members Static variables
in
enclosing and
non-static
context
method
prototypes
JVM creates one user thread for running a program. This thread is called main thread.
The main method of the class is called from the main thread. It dies when the main
method ends. If other user threads have been spawned from the main thread, program
keeps running even if main thread dies. Basically a program runs until all the user
threads (non-daemon threads) are dead.
A thread can be designated as a daemon thread by calling setDaemon(boolean)
method. This method should be called before the thread is started, otherwise
IllegalThreadStateException will be thrown.
A thread spawned by a daemon thread is a daemon thread.
Threads have priorities. Thread class have constants MAX_PRIORITY (10),
MIN_PRIORITY (1), NORM_PRIORITY (5)
A newly created thread gets its priority from the creating thread. Normally itll be
NORM_PRIORITY.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 47 of 109
.
getPriority and setPriority are the methods to deal with priority of threads.
Java leaves the implementation of thread scheduling to JVM developers. Two types
of scheduling can be done.
1. Pre-emptive Scheduling.
Ways for a thread to leave running state It can cease to be ready to execute ( by calling a blocking i/o method)
It can get pre-empted by a high-priority thread, which becomes ready to execute.
It can explicitly call a thread-scheduling method such as wait or suspend.
Blocked
Thread is waiting to get a lock on the
monitor.
(or waiting for a blocking i/o method)
Caused by the thread tried to execute
some synchronized code. (or a blocking
i/o method)
Can move to ready only when the lock
is available. ( or the i/o operation is
complete)
Waiting
Thread has been asked to wait. (by
means of wait method)
The thread already acquired the lock
and executed some synchronized code
before coming across a wait call.
Can move to ready only when it gets
notified (by means of notify or
notifyAll)
Locks on inner/outer objects are independent. Getting a lock on outer object doesnt
mean getting the lock on an inner object as well, that lock should be obtained
separately.
wait and notify should be called from synchronized code. This ensures that while
calling these methods the thread always has the lock on the object. If you have
wait/notify in non-synchronized code compiler wont catch this. At runtime, if the
thread doesnt have the lock while calling these methods, an
IllegalMonitorStateException is thrown.
Deadlocks can occur easily. e.g, Thread A locked Object A and waiting to get a lock
on Object B, but Thread B locked Object B and waiting to get a lock on Object A.
Theyll be in this state forever.
Its the programmers responsibility to avoid the deadlock. Always get the locks in
the same order.
While suspended, the thread keeps the locks it obtained so suspend is deprecated
in 1.2
Use of stop is also deprecated, instead use a flag in run method. Compiler wont warn
you, if you have statements after a call to stop, even though they are not reachable.
Object class is the ultimate ancestor of all classes. If there is no extends clause,
compiler inserts extends object. The following methods are defined in Object class.
All methods are public, if not specified otherwise.
Method
boolean equals(Object o)
Description
just does a == comparison, override in descendents to provide meaningful
comparison
Thread control. Two other versions of wait() accept timeout parameters and
may throw InterruptedException.
All constants and methods are public and static, just access using class name.
Two constants PI and E are specified.
Methods that implement Trigonometry functions are native.
All Math trig functions take angle input in radians.
Angle degrees * PI / 180 = Angle radians
Order of floating/double values:
-Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive
Numbers/Fractions --> Infinity
abs int, long, float, double versions available
floor greatest integer smaller than this number (look below towards the floor)
ceil smallest integer greater than this number (look above towards the ceiling)
For floor and ceil functions, if the argument is NaN or infinity or positive zero or
negative zero or already a value equal to a mathematical integer, the result is the same
as the argument.
For ceil, if the argument is less than zero but greater than 1.0, then the result is a
negative zero
random returns a double between 0.0(including) and 1.0(excluding)
round returns a long for double, returns an int for float. (closest int or long value to
the argument)
The result is rounded to an integer by adding , taking the floor of the result, and
casting the result to type int / long.
(int)Math.floor(a + 0.5f)
(long)Math.floor(a + 0.5d)
double rint(double) returns closest double equivalent to a mathematical integer. If two
values are equal, it returns the even integer value. rint(2.7) is 3, rint(2.5) is 2.
Math.min(-0.0, +0.0) returns 0.0, Math.max(-0.0, +0.0) returns 0.0, -0.0 == +0.0
returns true.
For a NaN or a negative argument, sqrt returns a NaN.
Every primitive type has a wrapper class (some names are different Integer,
Boolean, Character)
Wrapper class objects are immutable.
All Wrapper classes are final.
All wrapper classes, except Character, have a constructor accepting string. A Boolean
object, created by passing a string, will have a value of false for any input other than
true (case doesnt matter).
Numeric wrapper constructors will throw a NumberFormatException, if the passed
string is not a valid number. (empty strings and null strings also throw this exception)
equals also tests the class of the object, so even if an Integer object and a Long object
are having the same value, equals will return false.
NaNs can be tested successfully with equals method.
Float f1 = new Float(Float.NaN);
Float f2 = new Float(Float.NaN);
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 53 of 109
.
They can be created empty, from a string or with a capacity. An empty StringBuffer
is created with 16-character capacity. A StringBuffer created from a String has the
capacity of the length of String + 16. StringBuffers created with the specified capacity
has the exact capacity specified. Since they can grow dynamically in size without
bounds, capacity doesnt have much effect.
append, insert, setCharAt, reverse are used to manipulate the string buffer.
setLength changes the length, if the current content is larger than specified length, its
truncated. If it is smaller than the specified length, nulls are padded. This method
doesnt affect the capacity.
equals on StringBuffer does a shallow comparison. (same like ==) Will return true
only if the objects are same. Dont use it to test content equality
trim is not a StringBuffer method.
There is no relationship between String and StringBuffer. Both extend Object class.
String context means, + operator appearing with one String operand. String
concatenation cannot be applied to StringBuffers.
A new String buffer is created.
All operands are appended (by calling toString method, if needed)
Finally a string is returned by calling toString on the String Buffer.
String concatenation process will add a string with the value of null, if an object
reference is null and that object is appearing in a concatenation expression by itself.
But if we try to access its members or methods, a NullPointerException is thrown.
The same is true for arrays, array name is replaced with null, but trying to index it
when its null throws a NullPointerException.
Interface
Description
Collection
A basic interface that defines the operations that all the classes that
maintain collections of objects typically implement.
Extends Collection, sets that maintain unique elements. Set interface
is defined in terms of the equals operation
Extends Set, maintain the elements in a sorted order
Set
SortedSet
LinkedList (Nulls
OK)
Some of the operations in the collection interfaces are optional, meaning that the
implementing class may choose not to provide a proper implementation of such an
operation. In such a case, an UnsupportedOperationException is thrown when that
operation is invoked.
Interface
Methods
Description
Bulk
Operation
s
Collecti
on
Array
Operation
s
Iterators
Set
List
int size();
boolean isEmpty();
boolean
contains(Object
element);
boolean add(Object element);
boolean
remove(Object
element);
boolean containsAll(Collection
c);
boolean addAll(Collection c);
boolean
removeAll(Collection
c);
boolean retainAll(Collection c);
void clear();
Object[] toArray();
Object[] toArray(Object a[]);
These methods
combined with
Arrays.asList() method provide the
bridge between arrays and collections.
Iterator iterator();
Returns an iterator, to iterate the
Iterator is an interface which has collection.
these methods.
boolean hasNext();
The remove() method is the only
Object next();
recommended way to remove elements
void remove();
from a collection during the iteration.
The add() method returns false, if the
No new methods defined.
element is already in the Set. No
exceptions are thrown.
Object get(int index);
First index is 0, last index is size() 1.
Object set(int index, Object An
illegal
index
throws
element);
IndexOutOfBoundsException.
Element
void add(int index, Object
Access by
element);
Index
Object remove(int index);
boolean
addAll(int
index,
Collection c);
Element
int indexOf(Object o);
If the element is not found, return 1.
Search
int lastIndexOf(Object o);
ListIterator listIterator();
ListIterators additional methods:
ListIterator
listIterator(int
boolean hasPrevious();
List
index);
boolean previous();
Iterators
int nextIndex();
ListIterator extends Iterator. It
int prviousIndex();
allows
iteration
in
both
void set(Object o);
directions.
void add(Object o);
Map
Sorted
Set
Sorted
Map
Object firstKey();
Object lastKey();
Comparator comparator();
Method
public static Set singleton(Object
o)
public
static
List
singletonList(Object o)
public
static
Map
singletonMap(Object key, Object
value)
public static List nCopies (int n,
Object o)
Description
Returns an immutable set containing only the
specified object
Returns an immutable list containing only the
specified object
Returns an immutable map containing only the
specified key, value pair.
Returns an immutable list consisting of n copies of
the specified object. The newly allocated data
object is tiny (it contains a single reference to the
data object). This method is useful in combination
with the List.addAll method to grow lists.
The class Arrays, provides useful algorithms that operate on arrays. It also provides
the static asList() method, which can be used to create List views of arrays. Changes
to the List view affects the array and vice versa. The List size is the array size and
cannot be modified. The asList() method in the Arrays class and the toArray() method
in the Collection interface provide the bridge between arrays and collections.
Set mySet = new HashSet(Arrays.asList(myArray));
String[] strArray = (String[]) mySet.toArray();
All concrete implementations of the interfaces in java.util package are inherited from
abstract implementations of the interfaces. For example, HashSet extends
AbstractSet, which extends AbstractCollection. LinkedList extends AbstractList,
which extends AbstractCollection. These abstract implementations already provide
most of the heavy machinery by implementing relevant interfaces, so that customized
implementations of collections can be easily implemented using them.
BitSet class implements a vector of bits that grows as needed. Each component of the
bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 61 of 109
.
By default, all bits in the set initially have the value false. A BitSet has a size of 64,
when created without specifying any size.
ConcurrentModificationException exception (extends RuntimeException) may be
thrown by methods that have detected concurrent modification of a backing object
when such modification is not permissible.
For example, it is not permissible for one thread to modify a Collection while another
thread is iterating over it. In general, the results of the iteration are undefined under
these circumstances. Some Iterator implementations (including those of all the
collection implementations provided by the JDK) may choose to throw this exception
if this behavior is detected. Iterators that do this are known as fail-fast iterates, as they
fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an
undetermined time in the future.
Methods / Description
Dimension getSize()
void setSize(int width, int height)
void setSize(Dimension d)
Location
Point getLocation()
void setLocation(int x, int y)
void setLocation(Point p)
Size
and Rectangle getBounds()
Location
void setBounds (int x, int y, int width, int height)
void setBounds (Rectangle r)
Color
void setForeground(Color c)
void setBackground(Color c)
Font
void setFont(Font f)
void setFont(Font f)
Visibility
void setEnabled(boolean b)
and
void setVisible(boolean b)
Enabling
Container class extends Component. This class defines methods for nesting
components in a container.
Component add(Component comp)
Component add(Component comp, int index)
void add(Component comp, Object constraints)
void add(Component comp, Object constraints, int index)
void remove(int index)
void remove(Component comp)
void removeAll()
The following are the containers:
Contain
er
Panel
Description
Applet
Window
Frame
Dialog
ScrollPa
ne
Top-level containers (Window, Frame and Dialog) cannot be nested. They can
contain other containers and other components.
GUI components:
Component
Button
Description
A button with a textual label.
Constructors
new Button(Apply)
Canvas
No default appearance.
Can be sub-classed to create
custom drawing areas.
Checkbox
Checkbox(String label)
Toggling check box.
Default initial state is false.
getState(), setState(boolean state) - Checkbox(String label,
Events
Action event.
Mouse,
MouseMotio
n,
Key
events.
Item event
Choice
FileDialog
Label
List
methods
Can
be
grouped
with
a
CheckboxGroup to provide radio
behavior.
Checkboxgroup is not a subclass
of Component.
Checkboxgroup provides these
methods:
getSelectedCheckbox
and
setSelectedCheckbox(Checkbox
new)
A pull-down list
Can be populated by repeatedly
calling
addItem(String
item)
method.
Only the current choice is visible.
Subclass of Dialog
Open or Save file dialog, modal
Dialog automatically removed,
after user selects the file or hits
cancel.
getFile(), getDirectory() methods
can be used to get information
about the selected file.
Displays a single line of read-only
non-selectable text
Alignment can be
Label.LEFT,
Label.RIGHT
or
Label.CENTER
Scrollable vertical list of text
items.
No of visible rows can be
specified, if not specified layout
manager determines this.
Acquires a vertical scrollbar if
needed.
List class methods:
addItem(String),
addItem(String, int index)
getItem(int
index),
getItemCount()
getRows() no of visible rows
int getSelectedIndex()
int[] getSelectedIndexes()
String getSelectedItem()
boolean initialstate)
Checkbox(String label,
CheckBoxGroup
group)
Item event
FileDialog(Frame
parent, String title, int
mode)
Mode
can
be
FileDialog.LOAD or
FileDialog.SAVE
Label()
None
Label(String label)
Label(String label, int
align)
List()
List(int nVisibleRows)
List(int nVisibleRows,
boolean
multiSelectOK)
Item event
selecting or
deselecting
Action event
double
clicking
Scrollbar
TextField
TextArea
String[] getSelectedItems()
Orientation can be
Scrollbar.HORIZONT
AL
Scrollbar.VERTICAL
TextField() empty
Extends TextComponent
Single line of edit / display of text. field
TextField(int ncols)
Scrolled using arrow keys.
Depending on the font, number of size
TextField(String text)
displayable characters can vary.
But, never changes size once initial text
TextField(String text,
created.
int ncols) initial text
Methods from TextComponent:
and size
String getSelectedText()
String getText()
void
setEditable(boolean
editable)
void setText(String text)
TextArea() empty
Extends TextComponent
Multiple lines of edit/display of area
TextArea(int nrows, int
text.
ncols) size
Scrolled using arrow keys.
Can use the TextComponent TextArea(String text)
initial text
methods specified above.
Scroll parameter in last constructor TextArea(String text,
int nrows, int ncols)
form could be
initial text and size
TextArea.SCROLLBARS_BOT
TextArea(String text,
H,
int nrows, int ncols, int
Text event
Action event
Enter key is
pressed.
Text event
Pull-down menus are accessed via a menu bar, which can appear only on Frames.
All menu related components inherit from java.awt.MenuComponent
Steps to create and use a menu
Create an instance of MenuBar class
Attach it to the frame using setMenubar() method of Frame
Create an instance of Menu and populate it by adding MenuItems,
CheckboxMenuItems, separators and Menus. Use addSeparator() method to add
separators. Use add() method to add other items.
Attach the Menu to the MenuBar. Use add() method of Menubar to add a menu to
it. Use setHelpMenu to set a particular menu to appear always as right-most
menu.
Menu(String label) creates a Menu instance. Label is what displayed on the
Menubar. If this menu is used as a pull-down sub-menu, label is the menu items
label.
MenuItems generate Action Events.
CheckboxMenuItems generate Item Events.
If a component is added when the grid is full, a new column is created and the
entire container is re-laid out.
Border Layout Manager
Divides the container into 5 regions NORTH, SOUTH, EAST, WEST and
CENTER
When adding a component, specify which region to add. If nothing is specified,
CENTER is assumed by default.
Regions can be specified by the constant strings defined in BorderLayout (all
upper case) or using Strings (Title case, like North, South etc)
NORTH and SOUTH components height honored, but made as wide as the
container. Used for toolbars and status bars.
EAST and WEST components width honored, but made as tall as the container
(after the space taken by NORTH, SOUTH components). Used for scrollbars.
CENTER takes up the left over space. If there are no other components, it gets all
the space.
If no component is added to CENTER, containers background color is painted in
that space.
Each region can display only one component. If another component is added, it
hides the earlier component.
Card Layout Manager
Draws in time rather than space. Only one component displayed at a time.
Like a tabbed panel without tabs. (Can be used for wizards interface, i.e. by
clicking next, displays the next component)
Components added are given a name and methods on the CardLayout manager
can be invoked to show the component using this name. Also the manager
contains methods to iterate through the components. For all methods, the parent
container should be specified.
first(Container parent)
next(Container parent)
previous(Container parent)
last(Container parent)
show(Container parent, String name)
Component shown occupies the entire container. If it is smaller it is resized to fit
the entire size of the container. No visual clue is given about the container has
other components.
Gridbag Layout Manager
Like the GridLayout manger uses a rectangular grid.
Flexible. Components can occupy multiple cells. Also the width and height of the
cells need not be uniform. i.e A component may span multiple rows and columns
but the region it occupies is always rectangular. Components can have different
sizes (which is not the case with Grid layout)
Requires lot of constraints to be set for each component that is added.
GridBagConstraints class is used to specify the constraints.
Same GridBagConstraints object can be re-used by all the components.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 69 of 109
.
Name
of
constraints
int gridx
int gridy
Growth
Factor
double weigthx
double weigthy
Anchoring
int anchor
Filling
int fill
Padding
int ipadx
int ipady
Insets
Insets insets
Layout
Manager
Description
the Description
Column and row positions of the
upper left corner of the component in
the grid. Added relative to the
previous component if specified
GridBagConstraints.RELATIVE
Number of cells occupied by the
component horizontally and vertically
in the grid.
GridBagConstraints.REMAINDER
- specify this for last component
GridBagConstraints.RELATIVE
- specify this for next-to-last
component
How to use the extra space if
available.
Default
GridBagConstraints.RELA
TIVE in both directions
Constructors
GridLayout
BorderLayo
ut
CardLayout
GridbagLay
out
Lays
out
the
components in rowmajor order. Rows
growing from left to
right, top to bottom.
equivalent
to
components in a GridLayout(1,0)
specified rectangular GridLayout(int rows, int columns)
grid, from left to right
in each row and
filling rows from top
to bottom.
Up to 5 components BorderLayout()
can be placed in BorderLayout(int hgap, int vgap)
particular locations:
north, south, east,
west and center.
Components
are CardLayout()
handled as a stack of CardLayout(int hgap, int vgap)
indexed cards. Shows
only one at a time.
Customizable
and GridbagLayout()
flexible
layout
manager that lays out
the components in a
rectangular grid.
LEFT
Panel and
CENTER its
RIGHT
subclasses
(Applet)
N/A
None
NORTH
SOUTH
EAST
WEST
CENTER
N/A
Window
and
its
subclasses
(Dialog and
Frame)
None
Defined
None
in
GridBag
Constrain
ts class.
See the
above
table
ItemEvent
Source
Button when clicked
List when doubleclicked
MenuItem when clicked
TextField when Enter key is pressed
Scrollbar when adjustments are made
Event Types
ACTION_PERFORMED
ADJUSTMENT_VALUE_CHANG
ED
or ITEM_STATE_CHANGED
TextField
TextArea
TEXT_VALUE_CHANGED
Source
ComponentEv
ent
All
components
ContainerEve
nt
All containers
FocusEvent
All
components
InputEvent
KeyEvent
MouseEvent
All
components
All
components
All
components
Event Types
COMPONENT_SHOWN,
COMPONENT_HIDDEN,
COMPONENT_MOVED, COMPONENT_RESIZED
AWT handles this event automatically. Programs should not
handle this event.
COMPONENT_ADDED, COMPONENT_REMOVED
AWT handles this event automatically. Programs should not
handle this event.
FOCUS_GAINED, FOCUS_LOST
Receiving focus means the component will receive all the
keystrokes.
This is an abstract class. Parent of KeyEvent and MouseEvent.
Constants for key and mouse masks are defined in this class.
KEYPRESSED, KEYRELEASED, KEYTYPED (when a
character is typed)
MOUSE_PRESSED,
MOUSE_RELEASED,
MOUSE_CLICKED, MOUSE_DRAGGED, MOUSE_MOVED,
MOUSE_ENTERED, MOUSE_EXITED
PaintEvent
All
components
WindowEvent
All windows
Then the listener classes should be registered with the component that is the
source/originator of the event by calling the addXXXListener method on the
component. Listeners are unregistered by calling removeXXXListener method on the
component.
A component may have multiple listeners for any event type.
A component can be its own listener if it implements the necessary interface. Or it
can handle its events by implementing the processEvent method. (This is discussed in
explicit event enabling section)
All registered listeners with the component are notified (by invoking the methods
passing the event object). But the order of notification is not guaranteed (even if the
same component is registered as its own listener). Also the notification is not
guaranteed to occur on the same thread. Listeners should take cautions not to corrupt
the shared data. Access to any data shared between the listeners should be
synchronized.
Same listener object can implement multiple listener interfaces.
Event listeners are usually implemented as anonymous classes.
Event Type
Event Source
ActionEvent
Button
List
MenuItem
TextField
Scrollbar
AdjustmentEvent
ItemEvent
ComponentEvent
Choice
List
Checkbox
CheckboxMe
nuItem
TextField
TextArea
Component
ContainerEvent
Container
FocusEvent
Component
KeyEvent
Component
TextEvent
MouseEvent
Component
addAdjustmentListener
removeAdjustmentListner
addItemListener
removeItemListner
AdjustmentListener
addTextListener
removeTextListner
add ComponentListener
remove ComponentListner
addContainerListener
removeContainerListner
addFocusListener
removeFocusListner
addKeyListener
removeKeyListner
addMouseListener
removeMouseListner
addMouseMotionListener
removeMouseMotionListner
TextListener
ItemListener
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
Window
addWindowListener
removeWindowListner
WindowListener
ItemListener
TextListener
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListene
r
WindowListener
Event Adapters
Event Adapters are convenient classes implementing the event listener interfaces.
They provide empty bodies for the listener interface methods, so we can implement
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 76 of 109
.
only the methods of interest without providing empty implementation. They are
useful when implementing low-level event listeners.
There are 7 event adapter classes, one each for one low-level event listener interface.
Obviously, in semantic event listener interfaces, there is only one method, so there is
no need for event adapters.
Event adapters are usually implemented as anonymous classes.
update() restores the components background color and calls paint(). If you dont
want to erase the previously drawn content, override update() and just call paint()
from it. (A common practice).
Event handlers that need to modify the screen according to input events, usually store
the state information in instance variables and call repaint().
Images can be created from empty (using createImage(int width, int height) method)
or loaded from external image files (using getImage() method in Toolkit class). Then
they can be modified using the graphics context associated with the image. They can
be drawn on the component using the drawImage method of the Graphics context of
the component.
Between <APPLET> and </APPLET>, PARAM tags can be specified. These are
used to pass parameters from HTML page to the applet.
<PARAM NAME = name VALUE = value>
Applets call getParameter(name) to get the parameter. The name is not case sensitive
here.
The value returned by getParameter is case sensitive, it is returned as defined in the
HTML page.
If not defined, getParameter returns null.
Text specified between <APPLET> and </APPLET> is displayed by completely
applet ignorant browsers, who cannot understand even the <APPLET> tag.
If the applet class has only non-default constructors, applet viewer throws runtime
errors while loading the applet since the default constructor is not provided by the
JVM. But IE doesnt have this problem. But with applets always do the initialization
in the init method. Thats the normal practice.
Methods involved in applets lifecycle.
Method
Description
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 81 of 109
.
void start()
void stop()
void destroy()
void paint(Graphics g)
This method is called only once by the applet context to inform the
applet that it has been loaded into the system. Always followed by calls
to start() and paint() methods. Same purpose as a constructor. Use this
method to perform any initialization.
Applet context calls this method for the first time after calling init(), and
thereafter every time the applet page is made visible.
Applet context calls this method when it wants the applet to stop the
execution. This method is called when the applet page is no longer
visible.
This method is called to inform the applet that it should relinquish any
system resources that it had allocated. Stop() method is called prior to
this method.
Applets normally put all the rendering operations in this method.
Inside JVM, text is represented in 16 bit Unicode. For I/O, UTF (UCS (Universal
Character set) Transformation Format) is used. UTF uses as many bits as needed to
encode a character.
Often programs need to bring in information from an external source or send out
information to an external destination. The information can be anywhere: in a file, on
disk, somewhere on the network, in memory, or in another program. Also, it can be of
any type: objects, characters, images, or sounds.
To bring in information, a program opens a stream on an information source (a file,
memory or a socket) and reads the information serially. Similarly, a program can send
information to an external destination by opening a stream to a destination and
writing the information out serially.
No matter where the information is coming from or going to and no matter what type
of data is being read or written, the algorithms for reading and writing data is pretty
much always the same.
Reading
open a stream
while more information
read information
close the stream
Writing
open a stream
while more information
write information
close the stream
For this kind of general I/O Stream/Reader/Writer model is used. These classes are in
java.io package. They view the input/output as an ordered sequence of
bytes/characters.
We can create I/O chains of arbitrary length by chaining these classes.
These classes are divided into two class hierarchies based on the data type (either
characters or bytes) on which they operate. Streams operate on bytes while
Readers/Writers operate on chars.
However, it's often more convenient to group the classes based on their purpose
rather than on the data type they read and write. Thus, we can cross-group the streams
by whether they read from and write to data "sinks" (Low level streams) or process
the information as its being read or written (High level filter streams).
Low Level Streams/Data sink streams read from or write to specialized data sinks
such as strings, files, or pipes. Typically, for each reader or input stream intended to
read from a specific kind of input source, java.io contains a parallel writer or output
stream that can create it. The following table gives java.io's data sink streams.
Sink
Type
Character
Streams
Byte Streams
Purpose
Pipe
PipedReader,
PipedWriter
File
FileReader,
FileWriter
ByteArrayInputStre
am,
ByteArrayOutputStr
eam
Process
Character
Streams
Byte Streams
Purpose
Concatenatio
n
Object
Serialization
Data
Conversion
Counting
Peeking
Ahead
Printing
N/A
N/A
SequenceInputStrea
m
ObjectInputStream,
ObjectOutputStream
Reader and InputStream define similar APIs but for different data types. For example,
Reader contains these methods for reading characters and arrays of characters:
int read() throws IOException
int read(char cbuf[]) throws IOException
abstract int read(char cbuf[], int offset, int length) throws IOException
InputStream defines the same methods but for reading bytes and arrays of bytes:
abstract int read() throws IOException
int read(byte cbuf[]) throws IOException
int read(byte cbuf[], int offset, int length) throws IOException
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 85 of 109
.
Writer and OutputStream are similarly parallel. Writer defines these methods for
writing characters and arrays of characters:
int write(int c) throws IOException
abstract int write(char cbuf[])throws IOException
int write(char cbuf[], int offset, int length) throws IOException
And OutputStream defines the same methods but for bytes:
abstract int write(int c) throws IOException
int write(byte cbuf[]) throws IOException
int write(byte cbuf[], int offset, int length) throws IOException
Writer defines extra methods to write strings.
void write(String str) throws IOException
void write(String str, int offset, int length) throws IOException
Both Writer and OutputStream are abstract. Subclasses should provide
implementation for the write() method.
Constructors for some common streams, reader and writers:
FileInputStream(String name) throws FileNotFoundException
FileInputStream(File file) throws FileNotFoundException
FileInputStream(FileDescriptor fdObj)
FileOutputStream(String name) throws FileNotFoundException
FileOutputStream(String name, boolean append) throws FileNotFoundException
FileOutputStream (File file) throws FileNotFoundException
FileOutputStream (FileDescriptor fdObj)
DataInputStream(InputStream in)
DataOutputStream(OutputStream out)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
FileReader(File file) throws FileNotFoundException
FileReader (FileDescriptor fdObj)
FileReader (String name) throws FileNotFoundException
String
OutputStreamWriter(OutputStream out)
OutputStreamWriter (OutputStream out,
UnsupportedEncodingException
String
encodingName)
encodingName)
throws
throws
PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoflush)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoflush)
BufferedReader(Reader in)
BufferedReader(Reader in, int size)
BufferedWriter(Writer out)
BufferedWriter (Writer out, int size)
Encoding Name
8859_1
8859_2
8859_3
8859_4
UTF8
OutputStreamWriter and InputStreamReader are the only ones where you can specify
an encoding scheme apart from the default encoding scheme of the host system.
getEncoding method can be used to obtain the encoding scheme used.
With UTF-8 Normal ASCII characters are given 1 byte. All Java characters can be
encoded with at most 3 bytes, never more.
All of the streams--readers, writers, input streams, and output streams--are
automatically opened when created. You can close any stream explicitly by calling its
close method. Or the garbage collector can implicitly close it, which occurs when the
object is no longer referenced.
Closing the streams automatically flushes them. You can also call flush method.
New FileWriter(filename) or FileOutputStream(filename) will overwrite if
filename is existing or create a new file, if not existing. But we can specify the
append mode in the second argument.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 87 of 109
.
Print writers provide the ability to write textual representations of Java primitive
values. They have to be chained to the low-level streams or writers. Methods in this
class never throw an IOException.
PrintStream and PrintWriter classes can be created with autoflush feature, so that
each println method will automatically be written to the next available stream.
PrintStream is deprecated.(though System.out and System.err are still of this type)
System.in is of InputStream type.
System.in, System.out, System.err are automatically created for a program, by JVM.
Use buffered streams for improving performance.BufferedReader provides readLine
method.
User defined classes must implement Serializable or Externalizable interfaces to be
serialized.
Serializable is a marker interface with no methods. Externalizable has two methods to
be implemented readExternal(ObjectInput) and writeExternal(ObjectOutput).
ObjectOutputStream can write both Java Primitives and Object hierarchies. When a
compound object is serialized all its constituent objects that are serializable are also
serialized.
ObjectOutputStream implements ObjectOutput, which inherits from DataOutput.
All AWT components implement Serializable (Since Component class implements
it), so by default we can just use an ObjectOutputStream to serialize any AWT
component.
Description
Creates a File instance that represents the file with the specified
name in the specified directory
Creates a File instance that represents the file whose pathname is
the given path argument.
path, Creates a File instance whose pathname is the pathname of the
specified directory, followed by the separator character, followed
by the name argument.
File methods
Method
boolean canRead()
boolean canWrite()
boolean delete()
boolean exists()
Description
Tests if the application can read from the specified file.
Tests if the application can write to this file.
Deletes the file specified by this object.
Tests if this File exists.
boolean mkdir()
boolean mkdirs()
boolean
renameTo(File)
Instances of the file descriptor class serve as an opaque handle to the underlying
machine-specific structure representing an open file or an open socket.
Applications should not create their own file descriptors
RandomAccessFile lets you read/write at arbitrary places within files.
RAF provides methods to read/write bytes.
RAF also provides methods to read/write Java primitives and UTF strings. (RAF
implements the interfaces DataInput and DataOutput)
File and RAF instances should be closed when no longer needed.
All reading/writing operations throw an IOException. Need to catch or declare our
methods to be throwing that exception.
Read/Write methods throw a SecurityException if the application doesnt have rights
for the file.
RAF cannot be chained with streams/readers/writers.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 89 of 109
.
RAF Constructors
Constructor
RandomAccessFile(File file, String
mode)
throws FileNotFoundException,
IllegalArgumentException,
SecurityException
RandomAccessFile(String
name,
String
mode)
throws
FileNotFoundException,
IllegalArgumentException,
SecurityException
Description
Creates a random access file stream to read from,
and optionally to write to, the file specified by the
File argument.
The mode argument must either be equal to "r" or "rw", indicating either to open the
file for input or for both input and output.
Method
long getFilePointer()
throws IOException
void seek(long pos)
throws IOException
Description
Returns the offset from the beginning of the file, in bytes, at which
the next read or write occurs.
Sets the file-pointer offset, measured from the beginning of this
file, at which the next read or write occurs. The offset may be set
beyond the end of the file. Setting the offset beyond the end of the
file does not change the file length. The file length will change
only by writing after the offset has been set beyond the end of the
file.
long length() throws Returns the length of this file, measured in bytes.
IOException
Java Database Connectivity or in short JDBC is a technology that enables the java
program to manipulate data stored into the database. Here is the complete tutorial on
JDBC technology.
1.
What is JDBC?
JDBC is Java application programming interface that allows the Java programmers to access
database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun
Microsystems.
2.
4.
5.
6.
7.
8.
9.
JDBC is Java application programming interface that allows the Java programmers to
access database management system from Java code. It was developed by JavaSoft, a
subsidiary of Sun Microsystems.
Definition
Java Database Connectivity in short called as JDBC. It is a java API which enables the
java programs to execute SQL statements. It is an application programming interface that
defines how a java programmer can access the database in tabular format from Java
code using a set of standard interfaces and classes written in the Java programming
language.
JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the
same application. JDBC provides methods for querying and updating the data in
Relational Database Management system such as SQL, Oracle etc.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 91 of 109
.
Database connections
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 93 of 109
.
SQL statements
3.
Result Set
4.
Database metadata
5.
Prepared statements
6.
7.
8.
Callable statements
9.
Database drivers
The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager ensures
that the correct driver is used to access each data source. The Driver Manager is capable
of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
The location of the driver manager with respect to the JDBC drivers and the servlet is
shown in Figure 1.
Layers of the JDBC Architecture
A JDBC driver translates standard JDBC calls into a network or database protocol or into
a database library API call that facilitates communication with the database. This
translation layer provides JDBC applications with database independence. If the back-end
database changes, only the JDBC driver need be replaced with few code modifications
required. There are four distinct types of JDBC drivers.
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 94 of 109
.
Type 2 Java to Native API. Type 2 drivers use the Java Native Interface (JNI) to
make calls to a local database library API. This driver converts the JDBC calls into a
database specific call for databases such as SQL, ORACLE etc. This driver
communicates directly with the database server. It requires some native code to connect
to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type 1
drivers, Type 2 drivers require native database client libraries to be installed and
configured on the client machine.
Type 2 JDBC Architecture
Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure Java
drivers that use a proprietary network protocol to communicate with JDBC middleware
on the server. The middleware then translates the network protocol to database-specific
function calls. Type 3 drivers are the most flexible JDBC solution because they do not
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 95 of 109
.
Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement
a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the
database. Like Type 3 drivers, they do not require native database libraries and can be
deployed over the Internet without client installation. One drawback to Type 4 drivers is
that they are database specific. Unlike Type 3 drivers, if your back-end database changes,
you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are
available free of charge from the database manufacturer). However, because Type drivers
communicate directly with the database engine rather than through middleware or a
native library, they are usually the fastest JDBC drivers available. This driver directly
converts the java statements to SQL statements.
(See Figure 5.)
Type 4 JDBC Architecture
So, you may be asking yourself, "Which is the right type of driver for your application?"
Well, that depends on the requirements of your particular project. If you do not have the
opportunity or inclination to install and configure software on each client, you can rule
out Type 1 and Type 2 drivers.
However, if the cost of Type 3 or Type 4 drivers is prohibitive, Type 1 and type 2 drivers
may become more attractive because they are usually available free of charge. Price
aside, the debate will often boil down to whether to use Type 3 or Type 4 driver for a
particular application. In this case, you may need to weigh the benefits of flexibility and
interoperability against performance. Type 3 drivers offer your application the ability to
transparently access different types of databases, while Type 4 drivers usually exhibit
better performance and, like Type 1 and Type 2 drivers, may be available free if charge
from the database manufacturer.
Translates query obtained by JDBC into corresponding ODBC query, which is then handled by
the ODBC driver.
2.
3.
4.
There is some overhead associated with the translation work to go from JDBC to ODBC.
Advantages:
Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages:
1.
Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC
driver, then to the native database connectivity interface.
2.
3.
Considering the client-side software needed, this might not be suitable for applets.
This type of driver converts JDBC calls into calls to the client API for that database.
2.
Client -> JDBC Driver -> Vendor Client DB Library -> Database
Advantage
Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
1.
2.
3.
2.
3.
The JDBC Client driver written in java, communicates with a middleware-net-server using a
database independent protocol, and then this net server translates this request into database
commands for that database.
4.
5.
Client -> JDBC Driver -> Middleware-Net Server -> Any Database
Advantages
1.
Since the communication between client and the middleware server is database independent, there
is no need for the vendor db library on the client machine. Also the client to middleware need'nt be
changed for a new database.
2.
The Middleware Server (Can be a full fledged J2EE Application server) can provide typical
middleware services like caching (connections, query results, and so on), load balancing, logging,
auditing etc..
3.
4.
5.
At client side a single driver can handle any database.(It works provided the middlware supports
that database!!)
Disadvantages
1.
2.
An extra layer added may result in a time-bottleneck. But typically this is overcome by providing
efficient middleware
services described above.
Type 4 drivers are entirely written in Java that communicate directly with a vendor's database
through socket connections. No translation or middleware layers, are required, improving
performance.
2.
The driver converts JDBC calls into the vendor-specific database protocol so that client
applications can communicate directly with the database server.
3.
4.
e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to
jdbc:oracle:thin URL format.
5.
Client Machine -> Native protocol JDBC Driver -> Database server
This section gives you brief description of JDBC Steps for making connection with the
database, executing the query and showing the data to the user. In this application we
have connected to the MySQL database and retrieved the employee names from the
database. Here are the JDBC Steps to be followed while writing JDBC program:
Loading Driver
Establishing Connection
Executing Statements
Getting Results
Before explaining you the JDBC Steps for making connection to the database and
retrieving the employee from the tables, we will provide you the structure of the database
and sample data.
/*
Import JDBC core packages.
Following statement imports the java.sql package, which contains the
JDBC core API.
*/
import java.sql.*;
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 105 of 109
.
Loading Driver
Loading Database driver is very first step towards making JDBC connectivity with the
database. It is necessary to load the JDBC drivers before attempting to connect to the
database. The JDBC drivers automatically register themselves with the JDBC system when
loaded. Here is the code for loading the JDBC driver:
Class.forName(driver).newInstance();
Establishing Connection
In the above step we have loaded the database driver to be used. Now its time to make the
connection with the database server. In the Establishing Connection step we will logon to the
database with user name and password. Following code we have used to make the connection with
the database:
Last Modified on 12/11/2012
Collected by Rajeev K Mohan (rajeevkumar.mohan@gmail.com)Page 106 of 109
.
Executing Statements
In the previous step we established the connection with the database, now its time to execute
query against database. You can run any type of query against database to perform
database operations. In this example we will select all the rows from employee table. Here is
the code that actually execute the statements against database:
ResultSet res = st.executeQuery( "SELECT * FROM employee" );
Getting Results
In this step we receives the result of execute statement. In this case we will fetch the
employees records from the recordset object and show on the console. Here is the code:
while (res.next()) {
String employeeName = res.getInt( " employee_name " );
System.out.println( employeeName );
}
4. Executing a SQL statement with the Statement object, and returning a java ResultSet.
Statement interface defines methods that are used to interact with database via the execution of SQL
statements. The Statement class has three methods for executing statements: executeQuery(),
executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For
statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a
table, alter a table, or drop a table are all examples of DDL statements and are executed with the method
executeUpdate. execute() executes an SQL statement that is written as String object.
ResultSet provides access to a table of data generated by executing a Statement. The table rows are
retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method
is used to successively step through the rows of the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the columns in a
ResultSet. It is constructed from the Connection object.
Test JDBC Driver Installation
import javax.swing.JOptionPane;
public class TestJDBCDriverInstallation_Oracle {
public static void main(String[] args) {
StringBuffer output = new StringBuffer();
output.append("Testing oracle jdbc driver installation
\n");
try {
String className =
"sun.jdbc.odbc.JdbcOdbcDriver";
Class driverObject =
Class.forName(className);
output.append("Driver :
"+driverObject+"\n");
output.append("JDBC Driver Installation
Successful");
JOptionPane.showMessageDialog(null,
output);
} catch (Exception e) {
output = new StringBuffer();
output.append("JDBC Driver Installation
FAILED\n");
// JDBC Driver installation Failed
JOptionPane.showMessageDialog(null, output);
System.out.println("Failed: JDBC Driver Error: " +
e.getMessage());
}
}
}