Math Class Being An Option For Immutable Classes !!: Study Notes For Sun Certified Programmer For Java 2 Platform
Math Class Being An Option For Immutable Classes !!: Study Notes For Sun Certified Programmer For Java 2 Platform
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.
18.1E-5d is a valid double literal, E2d is not (since it starts with a letter,
compiler thinks that it’s an identifier)
19.Two types of variables.
1. Member variables
• Accessible anywhere in the class.
• Automatically initialized before invoking any constructor.
• Static variables are initialized at class load time.
• Can have the same name as the class.
2. Automatic variables(method local)
• Must be initialized explicitly. (Or, compiler will catch it.)
Object references can be initialized to null to make the compiler
happy. The following code won’t compile. Specify else part or
initialize the local variable explicitly.
20.Arrays are Java objects. If you create an array of 5 Strings, there will be 6
objects created.
21.Arrays should be
1. Declared. (int[] a; String b[]; Object []c; Size should not be
specified now)
2. Allocated (constructed). ( a = new int[10]; c = new
String[arraysize] )
3. Initialized. for (int i = 0; i < a.length; a[i++] = 0)
22.The above three can be done in one step.
int a[] = { 1, 2, 3 }; (or )
int a[] = new int[] { 1, 2, 3 }; But never specify the size with
the new statement.
23.Java arrays are static arrays. Size has to be specified at compile time.
Array.length returns array’s size. (Use Vectors for dynamic purposes).
24.Array size is never specified with the reference variable, it is always
maintained with the array object. It is maintained in array.length, which
is a final instance variable.
25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or
new int[10]
26.Arrays with zero elements can be created. args array to the main method
will be a zero element array if no command parameters are specified. In
this case args.length is 0.
27.Comma after the last initializer in array declaration is ignored.
57.finalize can be overloaded, but only the method with original finalize
signature will be called by gc.
58.finalize is not implicitly chained. A finalize method in sub-class should
call finalize in super class explicitly as its last action for proper
functioning. But compiler doesn’t enforce this check.
59.System.runFinalization can be used to run the finalizers (which have not
been executed before) for the objects eligible for garbage collection.
60.The following table specifies the color coding of javadoc standard. (May
be not applicable to 1.2)
Member Color
Instance method Red
Static method Green
Final variable Blue
Constructor Yellow
Study Notes for Sun Certified Programmer for Java 2 Platform
1. Unary operators.
1.1Increment and Decrement operators ++ --
We have postfix and prefix notation. In post-fix notation value of
the variable/expression is modified after the value is taken for the
execution of statement. In prefix notation, value of the
variable/expression is modified before the value is taken for the
execution of statement.
9. General
• In Java, No overflow or underflow of integers happens. i.e. The
values wrap around. Adding 1 to the maximum int value results in the
minimum value.
• Always keep in mind that operands are evaluated from left to
right, and the operations are executed in the order of precedence and
associativity.
• Unary Postfix operators and all binary operators (except
assignment operators) have left to right assoiciativity.
• All unary operators (except postfix operators), assignment
operators, ternary operator, object creation and cast operators have
right to left assoiciativity.
• Inspect the following code.
public class Precedence {
Study Notes for Sun Certified Programmer for Java 2 Platform
circuit or Conditional)
Logical OR (Short-circuit || Left to Right
or Conditional)
Ternary ?: Right to Left
Assignment = += -= *= /= %= <<= >>= Right to Left
>>>= &= ^= |=
Study Notes for Sun Certified Programmer for Java 2 Platform
Chapter 3 Modifiers
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 assigned a value in an
instance initializer or in every constructor. Otherwise the compiler
will complain.
• Final variables that are not assigned a value at the declaration
and method arguments that are marked final are called blank final
variables. They can be assigned a value at most once.
• Local variables can be declared final as well.
4. abstract
• Can be applied to classes and methods.
• For deferring implementation to sub-classes.
• Opposite of final, final can’t be sub-classed, abstract must be
sub-classed.
• A class should be declared abstract,
1. if it has any abstract methods.
2. if it doesn’t provide implementation to any of the abstract methods
it inherited
3. if it doesn’t provide implementation to any of the methods in an
interface that it says implementing.
• Just terminate the abstract method signature with a ‘;’, curly
braces will give a compiler error.
• A class can be abstract even if it doesn’t have any abstract
methods.
5. static
Study Notes for Sun Certified Programmer for Java 2 Platform
p = c;
p.doStuff(); // This will invoke
Parent.doStuff(), rather than Child.doStuff()
}
}
Study Notes for Sun Certified Programmer for Java 2 Platform
class Parent {
static int x = 100;
public static void doStuff() {
System.out.println("In Parent..doStuff");
System.out.println(x);
}
}
7. transient
• When an instance variable is declared as transient, then its
value need not persist when an object is stored. For example:
class T {
transient int a; // will not persist
int b; // will persist
}
Study Notes for Sun Certified Programmer for Java 2 Platform
8. synchronized
• Can be applied to methods or parts of methods only.
• Used to control access to critical code in multi-threaded
programs.
9. volatile
• Can be applied to variables only.
• Can be applied to static variables.
• Cannot be applied to final variables.
• Declaring a variable volatile indicates that it might be modified
asynchronously, so that all threads will get the correct value of the
variable.
• Used in multi-processor environments.
Abstract Y Y (Except N Y N N
anonymous
classes)
Static N Y Y Y N Y (static
initializer)
Native N N N Y N N
Transient N N Y N N N
Synchroni N N N Y N Y (part of
zed method, also
need to specify
an object on
which a lock
should be
obtained)
Volatile N N Y N N N
Study Notes for Sun Certified Programmer for Java 2 Platform
Conversion of Primitives
1. 3 types of conversion – assignment conversion, method call conversion
and arithmetic promotion
2. boolean may not be converted to/from any non-boolean type.
3. Widening conversions accepted. Narrowing conversions rejected.
4. byte, short can’t be converted to char and vice versa.
5. Arithmetic promotion
5.1Unary operators
• if the operand is byte, short or char {
convert it to int;
}
else {
do nothing; no conversion needed;
}
5.2Binary operators
• if one operand is double {
all double; convert the other operand to double;
}
else if one operand is float {
all float; convert the other operand to float;
}
Study Notes for Sun Certified Programmer for Java 2 Platform
int a = 3;
char d = a; // this won’t compile, since we’re assigning an int to
char
char e = -1; // this also won’t compile, since the value is not in the
range of char
char c = ‘9’; // this will compile, but ‘10’ or greater than ‘10’
will give error.
float f = 1.3; // this won’t compile, even though the value is within
float range. Here range is not important, but precision is. 1.3 is by
default a double, so a specific cast or f = 1.3f will work.
float f = 1/3; // this won’t compile, infinity error during division;
8. Method call conversions always look for the exact data type or a wider
one in the method signatures. They will not do narrowing conversions to
resolve methods, instead we will get a compile error.
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.
several unrelated classes may implement the same interface and if there’s
a need to deal with them collectively one way of treating them may be an
array of the interface type that they implement.
17.Primitive arrays can be converted to only the arrays of the same primitive
type. They cannot be converted to another type of primitive array. Only
object reference arrays can be converted / cast.
18.Primitive arrays can be converted to an Object reference, but not to an
Object[] reference. This is because all arrays (primitive arrays and
Object[]) are extended from Object.
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).
• .
• 0We 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
• a Cloneable interface reference, with casting, with runtime
check
• any class reference, with casting, with runtime check
• any array referenece, with casting, with runtime check
• any interface reference, with casting, with runtime check
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
expression’s data type. The following code won’t compile.
Study Notes for Sun Certified Programmer for Java 2 Platform
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. It’ll be executed only if
none of the case values match.
• switch can be nested. Nested case labels are independent, don’t
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 don’t 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
Study Notes for Sun Certified Programmer for Java 2 Platform
RuntimeException-->EmptyStackException, NoSuchElementException,
ArithmeticException, ArrayStoreException, ClassCastException,
IllegalArgumentException, IllegalMonitorStateException,
IndexOutOfBoundsException, NegativeArraySizeException,
NullPointerException, SecurityException.
IllegalArgumentException-->IllegalThreadStateException,
NumberFormatException
IndexOutOfBoundsException-->ArrayIndexOutOfBoundsException,
StringIndexOutOfBoundsException
IOException-->EOFException, FileNotFoundException,
InterruptedIOException, UTFDataFormatException,
MalformedURLException, ProtocolException, SockException,
UnknownHostException, UnknownServiceException.
Study Notes for Sun Certified Programmer for Java 2 Platform
Overloading Overriding
Signature has to be different. Just a Signature has to be the same.
difference in return type is not (including the return type)
enough.
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 Related directly to sub-classing.
are independent methods. Resolved Overrides the parent class method.
at compile-time based on method Resolved at run-time based on type of
signature. 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 super-class’s method.
super.super won’t work. Also, a class
outside the inheritance hierarchy can’t
use this technique.
Methods can be static or non-static. static methods don’t participate in
Since the methods are independent, overriding, since they are resolved at
it doesn’t matter. But if two compile time based on the type of
methods have the same signature, reference variable. A static method in
declaring one as static and another a sub-class can’t use ‘super’ (for the
Study Notes for Sun Certified Programmer for Java 2 Platform
as non-static does not provide a same reason that it can’t use ‘this’ for)
valid overload. It’s a compile time
error. Remember that a static method can’t
be overridden to be non-static and a
non-static method can’t 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)
There’s no limit on number of Each parent class method may be
overloaded methods a class can overridden at most once in any sub-
have. class. (That is, you cannot have two
identical methods in the same class)
System.out.println(s1.s); // prints S1
System.out.println(s1.getS()); // prints S1
System.out.println(s2.s); // prints S2
System.out.println(s2.getS()); // prints S2
s1 = s2;
System.out.println(s1.getS()); // prints S2 -
// since method is resolved at run
time
}
}
class S1 {
public String s = "S1";
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 STChild extends STParent {
double wealth = 200000.00;
System.out.println(wealth); // Prints
Child wealth
System.out.println(super.wealth); //
Prints Parent wealth
// Prints Parent wealth
System.out.println(((STParent)
(this)).wealth);
// Prints GrandParent wealth
System.out.println(((STGrandParent)
(this)).wealth);
}
}
class PTSuper {
public void hi() { // Super-class implementation
always calls superclass hello
hello();
}
private void hello() { // This method is not inherited
by subclasses, but exists in them.
// Commenting out both the methods in the
subclass show this.
// The test will then print "hello-Super" for
all three calls
// i.e. Always the super-class
implementations are called
System.out.println("hello-Super");
}
Study Notes for Sun Certified Programmer for Java 2 Platform
class PolyA {
private int f() { return 0; }
public int g() { return 3; }
}
Study Notes for Sun Certified Programmer for Java 2 Platform
Interfaces
Study Notes for Sun Certified Programmer for Java 2 Platform
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.
3. Local classes
• Defined inside a block (could be a method, a constructor,
a local block, a static initializer or an instance initializer).
Cannot be specified with static modifier.
• Cannot have any access modifier (since they are
effectively local to the block)
• Cannot declare any static members.(Even declared in a
static context)
• Can access all the features of the enclosing class (because
they are defined inside the method of the class) but can access
only final variables defined inside the method (including
method arguments). This is because the class can outlive the
method, but the method local variables will go out of scope – in
case of final variables, compiler makes a copy of those
variables to be used by the class. (New meaning for final)
• Since the names of local classes are not visible outside
the local context, references of these classes cannot be declared
outside. So their functionality could be accessed only via super-
class references (either interfaces or classes). Objects of those
Study Notes for Sun Certified Programmer for Java 2 Platform
4. Anonymous classes
• Anonymous classes are defined where they are
constructed. They can be created wherever a reference
expression can be used.
• Anonymous classes cannot have explicit constructors.
Instance initializers can be used to achieve the functionality of a
constructor.
• Typically used for creating objects on the fly.
• Anonymous classes can implement an interface (implicit
extension of Object) or explicitly extend a class. Cannot do
both.
Syntax: new interface name() { } or new class name()
{}
• Keywords “implements” and “extends” are not used in
anonymous classes.
• Abstract classes can be specified in the creation of an
anonymous class. The new class is a concrete class, which
automatically extends the abstract class.
• Discussion for local classes on static/non-static context,
accessing enclosing variables, and declaring static variables
also holds good for anonymous classes. In other words,
anonymous classes cannot be specified with static, but based on
the context, they could become static classes. In any case,
anonymous classes are not allowed to declare static members.
Study Notes for Sun Certified Programmer for Java 2 Platform
// Example 1
}
}
class Outer {
String name = "Vel";
class Inner {
String name = "Sharmi";
class InnerInner {
class InnerInnerInner {
System.out.println(Inner.this.name); // Prints
"Sharmi", Inner has declared 'name'
}
}
}
}
class Outer2 {
static String name = "Vel";
static class Inner2 {
static String name = "Sharmi";
class InnerInner2 {
public void doSomething() {
System.out.println(name); // prints "Sharmi", inner-most
hides outer-most
System.out.println(Outer2.name); // prints "Vel", explicit
reference to Outer2's static variable
Study Notes for Sun Certified Programmer for Java 2 Platform
// Example 2
// This is legal
// OuterClass.InnerClass ic = new OuterClass().new
InnerClass();
// ic.doSomething();
new OuterClass().doAnonymous();
}
}
class OuterClass {
final int a = 100;
private String secret = "Nothing serious";
System.out.println(this.getClass() + " - in
doSomething");
System.out.print("a = " + a + " secret = " + secret + "
arg = " + arg + " fa = " + fa);
System.out.println(" x = " + x + " y = " + y);
Chapter 7 Threads
• 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 it’ll be NORM_PRIORITY.
• getPriority and setPriority are the methods to deal with priority of
threads.
• Java leaves the implementation of thread scheduling to JVM developers.
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.
• Mactinosh JVM’s
• Windows JVM’s after Java 1.0.2
• Monitor (a.k.a Semaphore) is an object that can block and revive threads,
an object that controls client threads. Asks the client threads to wait and
notifies them when the time is right to continue, based on its state. In
strict Java terminology, any object that has some synchronized code is a
monitor.
• 2 ways to synchronize:
1. Synchronize the entire method
• Declare the method to be synchronized - very common practice.
• Thread should obtain the object’s lock.
2. Synchronize part of the method
• Have to pass an arbitrary object which lock is to be obtained to
execute the synchronized code block (part of a method).
• We can specify “this” in place object, to obtain very brief
locking – not very common.
Blocked Waiting
Thread is waiting to get a lock on Thread has been asked to wait. (by
the monitor. means of wait method)
(or waiting for a blocking i/o
method)
Caused by the thread tried to The thread already acquired the lock
execute some synchronized code. and executed some synchronized
Study Notes for Sun Certified Programmer for Java 2 Platform
Method Description
boolean equals(Object o) just does a == comparison, override in descendents to provide
meaningful comparison
final native void wait() Thread control. Two other versions of wait() accept timeout
final native void notify() parameters and may throw InterruptedException.
final native void
notifyAll()
native int hashcode() Returns a hash code value for the object.
If two objects are equal according to the equals method, then
calling the hashCode method on each of the two objects must
produce the same integer result.
protected Object clone() Creates a new object of the same class as this object. It then
throws initializes each of the new object's fields by assigning it the
CloneNotSupportedExce same value as the corresponding field in this object. No
ption constructor is called.
The clone method of class Object will only clone an object
CloneNotSupportedExce whose class indicates that it is willing for its instances to be
ption is a checked cloned. A class indicates that its instances can be cloned by
Exception declaring that it implements the Cloneable interface. Also the
method has to be made public to be called from outside the
class.
Arrays have a public clone method.
int ia[ ][ ] = { { 1 , 2}, null };
int ja[ ][ ] = (int[ ] [ ])ia.clone();
A clone of a multidimensional array is shallow, which is to
say that it creates only a single new array. Subarrays are
shared, so ia and ja are different but ia[0] and ja[0] are same.
final native Class Returns the runtime class of an object.
getClass()
String toString Returns the string representation of the object. Method in
Object returns a string consisting of the name of the class of
which the object is an instance, the at-sign character `@', and
Study Notes for Sun Certified Programmer for Java 2 Platform
(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 doesn’t 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.
• NaN’s can be tested successfully with equals method.
Float f1 = new Float(Float.NaN);
Float f2 = new Float(Float.NaN);
System.out.println( ""+ (f1 == f2)+" "+f1.equals(f2)+ " "+
(Float.NaN == Float.NaN) );
The above code will print false true false.
• Numeric wrappers have 6 methods to return the numeric value –
intValue(), longValue(), etc.
• valueOf method parses an input string (optionally accepts a radix in case
of int and long) and returns a new instance of wrapper class, on which it
was invoked. It’s a static method. For empty/invalid/null strings it throws
a NumberFormatException. For null strings valueOf in Float and Double
classes throw NullPointerException.
• parseInt and parseLong return primitive int and long values respectively,
parsing a string (optionally a radix). Throw a NumberFormatException
for invalid/empty/null strings.
Study Notes for Sun Certified Programmer for Java 2 Platform
• 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 it’s null throws a
NullPointerException.
Study Notes for Sun Certified Programmer for Java 2 Platform
Interface Description
Collection A basic interface that defines the operations that all the classes
that maintain collections of objects typically implement.
Set Extends Collection, sets that maintain unique elements. Set
interface is defined in terms of the equals operation
SortedSet Extends Set, maintain the elements in a sorted order
List Extends Collection, maintain elements in a sequential order,
duplicates allowed.
Map A basic interface that defines operations that classes that
represent mappings of keys to values typically implement
SortedMap Extends Map for maps that maintain their mappings in key order.
Interfaces
Data Set Sorted List Map SortedM
Structure Set ap
s used to
impleme
nt
Hash Table HashSet HashMap
(Nulls (Nulls OK)
OK) HashTable (No
Nulls)
Resizable ArrayList
Array (Nulls OK)
Vector(Nulls
OK)
Balanced TreeSe TreeMap
Tree t
Linked List LinkedList
(Nulls OK)
Method Description
public static Set Returns an immutable set containing only
singleton(Object o) the specified object
public static List Returns an immutable list containing only
singletonList(Object o) the specified object
public static Map Returns an immutable map containing only
singletonMap(Object key, the specified key, value pair.
Object value)
public static List nCopies (int Returns an immutable list consisting of n
n, Object o) 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.
examined, set, or cleared. One BitSet may be used to modify the contents
of another BitSet through logical AND, logical inclusive OR, and logical
exclusive OR operations.
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.
Chapter 10 Components
• Java’s building blocks for creating GUIs.
• All non-menu related components inherit from java.awt.Component, that
provides basic support for event handling, controlling component size,
color, font and drawing of components and their contents.
• Component class implements ImageObserver, MenuContainer and
Serializable interfaces. So all AWT components can be serialized and can
host pop-up menus.
• Component methods:
Contai Description
ner
Panel • Provides intermediate level of spatial organization and containment.
• Not a top-level window
• Does not have title, border or menubar.
• Can be recursively nested.
• Default layout is Flow layout.
Applet • Specialized Panel, run inside other applications (typically browsers)
• Changing the size of an applet is allowed or forbidden depending on
the browser.
• Default layout is Flow layout.
Windo • Top-level window without a title, border or menus.
w • Seldom used directly. Subclasses (Frame and Dialog) are used.
• Defines these methods:
• void pack() – Initiates layout management, window size
might be changed as a result
• void show() – Makes the window visible, also brings it to
front
• void dispose() – When a window is no longer needed, call
this to free resources.
Frame • Top-level window (optionally user-resizable and movable) with a
title-bar, an icon and menus.
• Typically the starting point of a GUI application.
• Default layout is Border layout.
Dialog • Top-level window (optionally user-resizable and movable) with a
title-bar.
• Doesn’t have icons or menus.
• Can be made modal.
• A parent frame needs to be specified to create a Dialog.
• Default layout is Border layout.
ScrollP • Can contain a single component. If the component is larger than the
ane scrollpane, it acquires vertical / horizontal scrollbars as specified in
the constructor.
• SCROLLBARS_AS_NEEDED – default, if nothing
specified
• SCROLLBARS_ALWAYS
Study Notes for Sun Certified Programmer for Java 2 Platform
• SCROLLBARS_NEVER
Orientation can be
Scrollbar.HORIZO
NTAL
Scrollbar.VERTIC
AL
TextFiel • Extends TextComponent TextField() – empty Text event
d • Single line of edit / display of field
text. TextField(int ncols) Action
• Scrolled using arrow keys. – size event –
• Depending on the font, number TextField(String Enter key is
of displayable characters can text) – initial text pressed.
vary. TextField(String
• But, never changes size once text, int ncols) –
created. initial text and size
• Methods from TextComponent:
• String
getSelectedText()
• String getText()
• void
setEditable(boolean
editable)
• void setText(String
text)
Study Notes for Sun Certified Programmer for Java 2 Platform
• 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 item’s label.
• MenuItems generate Action Events.
• CheckboxMenuItems generate Item Events.
Study Notes for Sun Certified Programmer for Java 2 Platform
component
GridBagConstraints.RELATIVE
- specify this for next-to-last
component
Growth double weigthx How to use the extra space if 0 for both, meaning that
Factor double weigthy available. the area allocated for
the component will not
grow beyond the
preferred size.
Anchorin int anchor Where a component should be GridBagConstraints.CE
g placed within its display area. NTER
Constants defined in
GridBagConstraints:
CENTER, NORTH,
NORTHEAST, EAST,
SOUTHEAST, SOUTH,
SOUTHWEST, WEST,
NORTHWEST
Filling int fill How the component is to stretch GridBagConstraints.NO
and fill its display area. NE
Constants defined in
GridBagConstraints:
NONE, BOTH, HORIZONTAL,
VERTICAL
Padding int ipadx Internal padding added to each 0 pixels in either
int ipady side of the component. direction
Dimension of the component
will grow to (width + 2 * ipadx)
and (height + 2 * ipady)
Insets Insets insets External padding (border) (0,0,0,0) (top, left,
around the component. bottom, right)
FlowLayo Lays out the FlowLayout() - center aligned, 5 LEFT Panel and
ut components in pixels gap both horizontally and CENTE its
row-major order. vertically R subclasses
Rows growing FlowLayout(int alignment) RIGHT (Applet)
from left to right, FlowLayout(int alignment, int
top to bottom. hgap, int vgap)
GridLayou Lays out the GridLayout() – equivalent to N/A None
t components in a GridLayout(1,0)
specified GridLayout(int rows, int
rectangular grid, columns)
from left to right
in each row and
filling rows from
top to bottom.
BorderLay Up to 5 BorderLayout() NORT Window
out components can BorderLayout(int hgap, int vgap) H and its
be placed in SOUTH subclasses
particular EAST (Dialog
locations: north, WEST and
south, east, west CENTE Frame)
and center. R
CardLayo Components are CardLayout() N/A None
ut handled as a stack CardLayout(int hgap, int vgap)
of indexed cards.
Shows only one at
a time.
GridbagLa Customizable and GridbagLayout() Defined None
yout flexible layout in
manager that lays GridBa
out the g
components in a Constrai
rectangular grid. nts
class.
See the
above
table
Study Notes for Sun Certified Programmer for Java 2 Platform
Chapter 12 Events
• Java 1.0’s original outward rippling event model had shortcomings.
- An event could only be handled by the component that originated
the event or one of its containers.
- No way to disable processing of irrelevant events.
• Java 1.1 introduced new “event delegation model”.
- A component may be told which objects should be notified when
the component generates a particular kind of event.
- If a component is not interested in an event type, those events
won’t be propagated.
• Both models are supported in Java 2, but the old model will eventually
disappear. Both models should not be mixed in a single program. If we
do that, the program is most likely to fail.
• Event delegation model’s main concepts: Event classes, Event listeners,
Explicit event enabling and Event adapter classes.
Event Classes
• Events are Java objects. All the pertinent information is encapsulated in
that object. The super class of all events is java.util.EventObject.
• This java.util.EventObject class defines a method that returns the object
that generated the event:
Object getSource()
• All events related to AWT are in java.awt.event package. AWTEvent is
the abstract super class of all AWT events. This class defines a method
that returns the ID of the event. All events define constants to represent
the type of event.
int getID() – returns an int in the form of an integer value that
identifies the type of event.
• It is useful to divide the event classes into Semantic events and Low-level
events.
• Semantic Events –
These classes are used for high-level semantic events, to represent user
interaction with GUI. ActionEvent, AdjustmentEvent, ItemEvent,
TextEvent
addMouseMotionListener MouseMotionListener
removeMouseMotionListn
er
WindowEve Window addWindowListener WindowListener
nt removeWindowListner
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 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.
Chapter 13 Painting
• Some objects have default appearance. When they are created, OS
decorates with a pre-defined appearance.
• Some components don’t have any intrinsic appearance. These are Applet,
Panel, Frame and Canvas. For these objects paint() method is used to
render them.
public void paint(Graphics g)
• The paint() method provides a graphics context (an instance of Graphics
class) for drawing. This is passed as a method argument.
• A Graphics object encapsulates state information needed for the basic
rendering operations that Java supports. This state information includes
the following properties:
• The Component object on which to draw.
• A translation origin for rendering and clipping coordinates.
• The current clip.
• The current color.
• The current font.
• The current logical pixel operation function (XOR or Paint).
• The current XOR alternation color.
• We can use this Graphics object to achieve the following functionality:
1. Selecting a color – g.setColor(Color)
There are 13 predefined colors in Color class. Or create a new
color using Color(R,G,B)
2. Selecting a Font – g.setFont(Font)
A Font is created by Font(String name, int style, int size)
3. Drawing and Filling – Various draw, fill methods
4. Clipping – g.setClip(Shape) or g.setClip(x, y, width, height)
• Graphics class is an abstract class. It cannot be created. But an instance
can be obtained in 2 ways.
1. Every component has an associated graphics context. Get this
using getGraphics method.
2. Given an existing Graphics object, call create() on that object to
create a new one.
In both cases, after its use call dispose method on Graphics, to free the
resources. We shouldn’t call dispose on the graphics context passed into
paint() method, since it’s just temporarily made available.
• JVM calls paint() spontaneously under 4 circumstances
1. After exposure
2. After de-iconification
Study Notes for Sun Certified Programmer for Java 2 Platform
Method Description
URL Returns the document URL, i.e. the URL of the HTML file in
getDocumentBase() which the applet is embedded.
URL getCodeBase() Returns the base URL, i.e. the URL of the applet class file that
contains the applet.
void Applet can request the applet context to display messages in its
showStatus(String “status window”.
msg)
Study Notes for Sun Certified Programmer for Java 2 Platform
Chapter 15 I/O
• 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 Writing
open a stream open a stream
while more information while more information
read information write information
close the stream close the stream
Sink Character
Byte Streams Purpose
Type Streams
Use these streams to read from and
CharArrayRe
ByteArrayInputSt
write to memory. You create these
ader, ream,
streams on an existing array and then
CharArrayWr
ByteArrayOutput
use the read and write methods to read
iter Stream
from or write to the array.
Use StringReader to read characters
Memo from a String as it lives in memory.
ry Use StringWriter to write to a String.
StringWriter collects the characters
StringReader, StringBufferInput
written to it in a StringBuffer, which
StringWriter Stream
can then be converted to a String.
StringBufferInputStream is similar to
StringReader, except that it reads bytes
from a StringBuffer.
PipedInputStrea Implement the input and output
PipedReader, m, components of a pipe. Pipes are used to
Pipe
PipedWriter PipedOutputStrea channel the output from one program
m (or thread) into the input of another.
Collectively called file streams, these
FileReader, FileInputStream,
File streams are used to read from or write
FileWriter FileOutputStream
to a file on the native file system.
Character
Process Byte Streams Purpose
Streams
Buffer data while reading or
writing, thereby reducing the
BufferedRead BufferedInputStre
number of accesses required on
er, am,
Buffering the original data source.
BufferedWrite BufferedOutputStr
Buffered streams are typically
r eam
more efficient than similar
nonbuffered streams.
Abstract classes, like their
FilterInputStream, parents. They define the
FilterReader,
Filtering FilterOutputStrea interface for filter streams,
FilterWriter
m which filter data as it's being
read or written.
A reader and writer pair that
forms the bridge between byte
streams and character streams.
An InputStreamReader reads
bytes from an InputStream and
converts them to characters
Converting InputStreamR using either the default
between eader, character-encoding or a
N/A
Bytes and OutputStream character-encoding specified by
Characters Writer name. Similarly, an
OutputStreamWriter converts
characters to bytes using either
the default character-encoding or
a character-encoding specified
by name and then writes those
bytes to an OutputStream.
Concatenati SequenceInputStr Concatenates multiple input
N/A
on eam streams into one input stream.
ObjectInputStrea
Object
m,
Serializatio N/A Used to serialize objects.
ObjectOutputStrea
n
m
Data N/A DataInputStream, Read or write primitive Java data
Conversion DataOutputStream types in a machine-independent
format. Implement
DataInput/DataOutput
Study Notes for Sun Certified Programmer for Java 2 Platform
interfaces.
LineNumberR LineNumberInput Keeps track of line numbers
Counting
eader Stream while reading.
Two input streams each with a
1-character (or byte) pushback
buffer. Sometimes, when reading
data from a stream, you will find
it useful to peek at the next item
Peeking PushbackRead PushbackInputStr in the stream in order to decide
Ahead er eam what to do next. However, if you
do peek ahead, you'll need to put
the item back so that it can be
read again and processed
normally. Certain kinds of
parsers need this functionality.
Contain convenient printing
methods. These are the easiest
Printing PrintWriter PrintStream streams to write to, so you will
often see other writable streams
wrapped in one of these.
• 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
Also, both Reader and InputStream provide methods for marking a
location in the stream, skipping input, and resetting the current position.
DataInputStream(InputStream in)
DataOutputStream(OutputStream out)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String encodingName) throws
UnsupportedEncodingException
OutputStreamWriter(OutputStream out)
OutputStreamWriter (OutputStream out, String encodingName)
throws UnsupportedEncodingException
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)
Constructor Description
File(File dir,
Creates a File instance that represents the file with the
String name) specified name in the specified directory
File(String path) Creates a File instance that represents the file whose
pathname is the given path argument.
File(String path, Creates a File instance whose pathname is the pathname
String name) of the specified directory, followed by the separator
character, followed by the name argument.
• File methods
Method Description
boolean canRead() Tests if the application can read from the specified
file.
boolean canWrite() Tests if the application can write to this file.
boolean delete() Deletes the file specified by this object.
boolean exists() Tests if this File exists.
String Returns the absolute pathname of the file represented
getAbsolutePath() by this object.
String Returns the canonical form of this File object's
getCanonicalPath() pathname.
.. and . are resolved.
String getName() Returns the name of the file represented by this object.
String getParent() Returns the parent part of the pathname of this File
object, or null if the name has no parent part.
String getPath() Returns the pathname of the file represented by this
object.
boolean Tests if the file represented by this File object is an
isAbsolute() absolute pathname.
boolean Tests if the file represented by this File object is a
isDirectory() directory.
boolean isFile() Tests if the file represented by this File object is a
"normal" file.
long lastModified() Returns the time that the file represented by this File
Study Notes for Sun Certified Programmer for Java 2 Platform
• RAF Constructors
Constructor Description
Study Notes for Sun Certified Programmer for Java 2 Platform
• 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 Description
long Returns the offset from the beginning of the file, in
getFilePointer() bytes, at which the next read or write occurs.
throws IOException
void seek(long pos) Sets the file-pointer offset, measured from the beginning
throws IOException 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