Dicas Certificacao
Dicas Certificacao
Dicas Certificacao
This document has material collected from a lot of resources. I have listed some of the resources here. I’m
thankful to all those great people. Anything I forgot to mention is not intentional.
1. Java 1.1 Certification Study Guide by Simon Roberts and Philip Heller.
2. Java 2 Certification Study Guide by Simon Roberts, Philip Heller and Michael Ernst.
3. Java 2 Exam Cram by Bill Brogden
4. A Programmer’s 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/overview-summary.html
8. Marcus Green - http://www.jchq.net
9. Java Ranch Discussions and Archives - http://www.javaranch.com/
10. Maha Anna’s Resource Page - http://www.javaranch.com/maha/
11. Jyothi's page - http://www.geocities.com/SiliconValley/Network/3693/
12. Dylan Walsh’s exam revision page - http://indigo.ie/~dywalsh/certification/index.htm
13. And an ever-increasing list of web sites regarding SCJP certification.
This document is mostly organized like the RHE book, as far as the chapter names and the order. Various
facts, explanations, things to remember, tips, sample code are presented as you go along with each chapter.
Please remember that, as this document is prepared as a side-product along the path to my certification,
there may not be a logical order in everything, though I tried to put it that way. Some points might be
repeated, and some things might rely on a fact that was mentioned elsewhere.
If you find any errors or have something to say as feedback, please e-mail at [email protected]
Exam Objectives
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.
public String testMethod ( int a) {
String tmp;
if ( a > 0 ) tmp = “Positive”; // Specify else part to make this code compile.
return tmp;
}
• Can have the same name as a member variable, resolution is based on scope.
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.
Member Color
Instance method Red
Static method Green
Final variable Blue
Constructor Yellow
Chapter 2 Operators and assignments
1. Unary operators.
1.1 Increment 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 {
final public static void main(String args[]) {
int i = 0;
i = i++;
i = i++;
i = i++;
System.out.println(i); // prints 0, since = operator has the lowest precedence.
1. Modifiers are Java keywords that provide information to compiler about the nature of the code, data
and classes.
2. Access modifiers – public, protected, private
• Only applied to class level variables. Method variables are visible only inside the method.
• Can be applied to class itself (only to inner classes declared at class level, no such thing as
protected or private top level class)
• Can be applied to methods and constructors.
• If a class is accessible, it doesn’t mean, the members are also accessible. Members’ accessibility
determines what is accessible and what is not. But if the class is not accessible, the members are
not accessible, even though they are declared public.
• If no access modifier is specified, then the accessibility is default package visibility. All classes in
the same package can access the feature. It’s called as friendly access. But friendly is not a Java
keyword. Same directory is same package in Java’s consideration.
• ‘private’ means only the class can access it, not even sub-classes. So, it’ll cause access denial to a
sub-class’s own variable/method.
• These modifiers dictate, which classes can access the features. An instance of a class can access
the private features of another instance of the same class.
• ‘protected’ means all classes in the same package (like default) and sub-classes in any package can
access the features. But a subclass in another package can access the protected members in the
super-class via only the references of subclass or its subclasses. A subclass in the same package
doesn’t have this restriction. This ensures that classes from other packages are accessing only the
members that are part of their inheritance hierarchy.
• Methods cannot be overridden to be more private. Only the direction shown in following figure is
permitted from parent classes to 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 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
• Can be applied to nested classes, methods, variables, free floating code-block (static initializer)
• Static variables are initialized at class load time. A class has only one copy of these variables.
• Static methods can access only static variables. (They have no this)
• Access by class name is a recommended way to access static methods/variables.
• Static initializer code is run at class load time.
• Static methods may not be overridden to be non-static.
• Non-static methods may not be overridden to be static.
• Abstract methods may not be static.
• Local variables cannot be declared as static.
• Actually, static methods are not participating in the usual overriding mechanism of invoking the
methods based on the class of the object at runtime. Static method binding is done at compile time,
so the method to be invoked is determined by the type of reference variable rather than the actual
type of the object it holds at runtime.
Let’s say a sub-class has a static method which ‘overrides’ a static method in a parent class. If you
have a reference variable of parent class type and you assign a child class object to that variable
and invoke the static method, the method invoked will be the parent class method, not the child
class method. The following code explains this.
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);
}
}
Modifier Class Inner classes Variable Method Constructor Free floating Code block
(Except local and
anonymous
classes)
public Y Y Y Y Y N
protected N Y Y Y Y N
(friendly) Y Y (OK for all) Y Y Y N
No access
modifier
private N Y Y Y Y N
final Y Y (Except Y Y N N
anonymous
classes)
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
synchronized N N N Y N Y (part of method, also
need to specify an
object on which a lock
should be obtained)
volatile N N Y N N N
Chapter 4 Converting and Casting
Unary Numeric Promotion
Contexts:
• Operand of the unary arithmetic operators + and –
• Operand of the unary integer bit-wise complement operator ~
• During array creation, for example new int[x], where the dimension expression x must
evaluate to an int value.
• Indexing array elements, for example table[‘a’], where the index expression must evaluate to
an int value.
• Individual operands of the shift operators.
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.1 Unary operators
• if the operand is byte, short or char {
convert it to int;
}
else {
do nothing; no conversion needed;
}
5.2 Binary 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;
}
else if one operand is long {
all long; convert the other operand to long;
}
else {
all int; convert all to int;
}
6. When assigning a literal value to a variable, the range of the variable’s data type is checked against the
value of the literal and assignment is allowed or compiler will produce an error.
char c = 3; // this will compile, even though a numeric literal is by default an int since the range of
char will accept the value
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
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 will compile, since RHS evaluates to an int.
Float f = 1.0 / 3.0; // this won’t compile, since RHS evaluates to a double.
7. Also when assigning a final variable to a variable, even if the final variable’s data type is wider than
the variable, if the value is within the range of the variable an implicit conversion is done.
byte b;
final int a = 10;
b = a; // Legal, since value of ‘a’ is determinable and within range of b
final int x = a;
b = x; // Legal, since value of ‘x’ is determinable and within range of b
int y;
final int z = y;
b = z; // Illegal, since value of ‘z’ is not determinable
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.
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.
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.
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
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 there’s 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, it’ll 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 that’s being re-thrown in the catch block. 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 you’ve handled the exceptions or you’ve declared the
methods as throwing the exceptions. Hence the name checked exceptions.
• If there’s 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 sub-classes 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 sub-class 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.
Here is the exception hierarchy.
Object
|
|
Throwable
| |
| |
| |
| Error
|
|
Exception-->ClassNotFoundException, ClassNotSupportedException, IllegalAccessException,
InstantiationException, IterruptedException, NoSuchMethodException, RuntimeException,
AWTException, IOException
IllegalArgumentException-->IllegalThreadStateException, NumberFormatException
IndexOutOfBoundsException-->ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException
Overloading Overriding
Signature has to be different. Just a difference in Signature has to be the same. (including the return
return type is not enough. 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 independent Related directly to sub-classing. Overrides the parent
methods. Resolved at compile-time based on class method. Resolved at run-time based on type of
method signature. the object.
Can call each other by providing appropriate Overriding method can call overridden method by
argument list. 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. Since the static methods don’t participate in overriding, since
methods are independent, it doesn’t matter. But if they are resolved at compile time based on the type of
two methods have the same signature, declaring reference variable. A static method in a sub-class can’t
one as static and another as non-static does not use ‘super’ (for the same reason that it can’t use ‘this’
provide a valid overload. It’s a compile time for)
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 overloaded Each parent class method may be overridden at most
methods a class can have. once in any sub-class. (That is, you cannot have two
identical methods in the same class)
• Variables can also be overridden, it’s known as shadowing or hiding. But, member variable
references are resolved at compile-time. So at the runtime, if the class of the object referred
by a parent class reference variable, is in fact a sub-class having a shadowing member
variable, only the parent class variable is accessed, since it’s already resolved at compile time
based on the reference variable type. Only methods are resolved at run-time.
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";
• 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 don’t 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)
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);
}
}
• 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.
• JVM knows about the variable’s 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 super-classes. 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.
• An inherited method, which was not abstract on the super-class, can be declared abstract in a
sub-class (thereby making the sub-class abstract). There is no restriction. In the same token, a
subclass can be declared abstract regardless of whether the super-class was abstract or not.
• Private members are not inherited, but they do exist in the sub-classes. Since the private
methods are not inherited, they cannot be overridden. A method in a subclass with the same
signature as a private method in the super-class is essentially a new method, independent from
super-class, since the private method in the super-class is not visible in the sub-class.
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");
}
}
void hello() throws Exception { // This method is independent from super-class hello
// Evident from, it's allowed to throw Exception
System.out.println("hello-Sub");
}
}
• 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;
class PolyA {
private int f() { return 0; }
public int g() { return 3; }
}
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. Can’t 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.
• Any accessibility modifier can be specified.
• Interfaces are implicitly static (static modifier also can be specified). They can have any
accessibility modifier. There are no non-static inner, local or anonymous interfaces.
2. Non-static inner classes
• Declared as a class member without static.
• An instance of a non-static inner class can exist only with an instance of its enclosing
class. So it always has to be created within a context of an outer instance.
• Just like other non-static features of a class. Can access all the features (even private) of
the enclosing outer class. Have an implicit reference to the enclosing instance.
• Cannot have any static members.
• Can have any access modifier.
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 class types are
created inside methods and returned as super-class type references to the outside world.
This is the reason that they can only access final variables within the local block. That
way, the value of the variable can be always made available to the objects returned from
the local context to outside world.
• Cannot be specified with static modifier. But if they are declared inside a static context
such as a static method or a static initializer, they become static classes. They can only
access static members of the enclosing class and local final variables. But this doesn’t
mean they cannot access any non-static features inherited from super classes. These
features are their own, obtained via the inheritance hierarchy. They can be accessed
normally with ‘this’ or ‘super’.
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. Based on the context, non-static/static features of outer classes are available to
anonymous classes. Local final variables are always available to them.
• One enclosing class can have multiple instances of inner classes.
• Inner classes can have synchronous methods. But calling those methods obtains the lock for
inner object only not the outer object. If you need to synchronize an inner class method based
on outer object, outer object lock must be obtained explicitly. Locks on inner object and outer
object are independent.
• Nested classes can extend any class or can implement any interface. No restrictions.
• All nested classes (except anonymous classes) can be abstract or final.
• Classes can be nested to any depth. Top-level static classes can be nested only within other
static top-level classes or interfaces. Deeply nested classes also have access to all variables of
the outer-most enclosing class (as well the immediate enclosing class’s)
• Member inner classes can be forward referenced. Local inner classes cannot be.
• An inner class variable can shadow an outer class variable. In this case, an outer class variable
can be referred as (outerclassname.this.variablename).
• Outer class variables are accessible within the inner class, but they are not inherited. They
don’t become members of the inner class. This is different from inheritance. (Outer class
cannot be referred using ‘super’, and outer class variables cannot be accessed using ‘this’)
• An inner class variable can shadow an outer class variable. If the inner class is sub-classed
within the same outer class, the variable has to be qualified explicitly in the sub-class. To
fully qualify the variable, use classname.this.variablename. If we don’t correctly qualify the
variable, a compiler error will occur. (Note that this does not happen in multiple levels of
inheritance where an upper-most super-class’s variable is silently shadowed by the most
recent super-class variable or in multiple levels of nested inner classes where an inner-most
class’s variable silently shadows an outer-most class’s variable. Problem comes only when
these two hierarchy chains (inheritance and containment) clash.)
• If the inner class is sub-classed outside of the outer class (only possible with top-level nested
classes) explicit qualification is not needed (it becomes regular class inheritance)
// Example 1
}
}
class Outer {
String name = "Vel";
class Inner {
String name = "Sharmi";
class InnerInner {
class InnerInnerInner {
// error, variable is not inherited from the outer class, it can be just accessible
// System.out.println(this.name);
// System.out.println(InnerInner.this.name);
// System.out.println(InnerInnerInner.this.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
// System.out.println(this.name); // error, 'name' is not inherited
// System.out.println(super.name); // error, super refers to Object
}
}
}
// 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";
• 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. 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.
• Mactinosh JVM’s
• Windows JVM’s after Java 1.0.2
• Different states of a thread:
1. Yielding
• Yield is a static method. Operates on current thread.
• Moves the thread from running to ready state.
• If there are no threads in ready state, the yielded thread may continue execution, otherwise it may
have to compete with the other threads to run.
• Run the threads that are doing time-consuming operations with a low priority and call yield
periodically from those threads to avoid those threads locking up the CPU.
2. Sleeping
• Sleep is also a static method.
• Sleeps for a certain amount of time. (passing time without doing anything and w/o using CPU)
• Two overloaded versions – one with milliseconds, one with milliseconds and nanoseconds.
• Throws an InterruptedException.(must be caught)
• After the time expires, the sleeping thread goes to ready state. It may not execute immediately
after the time expires. If there are other threads in ready state, it may have to compete with those
threads to run. The correct statement is the sleeping thread would execute some time after the
specified time period has elapsed.
• If interrupt method is invoked on a sleeping thread, the thread moves to ready state. The next time
it begins running, it executes the InterruptedException handler.
3. Suspending
• Suspend and resume are instance methods and are deprecated in 1.2
• A thread that receives a suspend call, goes to suspended state and stays there until it receives a
resume call on it.
• A thread can suspend it itself, or another thread can suspend it.
• But, a thread can be resumed only by another thread.
• Calling resume on a thread that is not suspended has no effect.
• Compiler won’t warn you if suspend and resume are successive statements, although the thread
may not be able to be restarted.
4. Blocking
• Methods that are performing I/O have to wait for some occurrence in the outside world to happen
before they can proceed. This behavior is blocking.
• If a method needs to wait an indeterminable amount of time until some I/O takes place, then the
thread should graciously step out of the CPU. All Java I/O methods behave this way.
• A thread can also become blocked, if it failed to acquire the lock of a monitor.
5. Waiting
• wait, notify and notifyAll methods are not called on Thread, they’re called on Object. Because the
object is the one which controls the threads in this case. It asks the threads to wait and then
notifies when its state changes. It’s called a monitor.
• Wait puts an executing thread into waiting state.(to the monitor’s waiting pool)
• Notify moves one thread in the monitor’s waiting pool to ready state. We cannot control which
thread is being notified. notifyAll is recommended.
• NotifyAll moves all threads in the monitor’s waiting pool to ready.
• These methods can only be called from synchronized code, or an IllegalMonitorStateException
will be thrown. In other words, only the threads that obtained the object’s lock can call these
methods.
Blocked Waiting
Thread is waiting to get a lock on the monitor. Thread has been asked to wait. (by means of
(or waiting for a blocking i/o method) wait method)
Caused by the thread tried to execute some The thread already acquired the lock and
synchronized code. (or a blocking i/o method) executed some synchronized code before
coming across a wait call.
Can move to ready only when the lock is Can move to ready only when it gets notified
available. ( or the i/o operation is complete) (by means of notify or notifyAll)
• 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 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 parameters and may throw
final native void notify() 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() throws Creates a new object of the same class as this object. It then initializes each of the new
CloneNotSupportedException object's fields by assigning it the same value as the corresponding field in this object. No
constructor is called.
CloneNotSupportedException The clone method of class Object will only clone an object whose class indicates that it is
is a checked Exception willing for its instances to be cloned. A class indicates that its instances can be cloned by
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 getClass() Returns the runtime class of an object.
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 the
unsigned hexadecimal representation of the hash code of the object. Override to provide
useful information.
protected void finalize() throws Called by the garbage collector on an object when garbage collection determines that there
Throwable are no more references to the object.
Any exception thrown by the finalize method causes the finalization of this object to be
halted, but is otherwise ignored.
The finalize method in Object does nothing. A subclass overrides the finalize method to
dispose of system resources or to perform other cleanup.
• 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.
• Numeric wrappers have overloaded toString methods, which accept corresponding primitive values
(also a radix in case of int,long) and return a string.
• Void class represents void primitive type. It’s not instantiable. Just a placeholder 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 it’s null throws a NullPointerException.
Chapter 9 java.util package
• A collection (a.k.a bag or multiset) allows a group of objects to be treated as a single unit. Arbitrary
objects can be stored, retrieved and manipulated as elements of these collections.
• Collections Framework presents a set of standard utility classes to manage such collections.
1. It contains ‘core interfaces’ which allow collections to be manipulated independent of their
implementations. These interfaces define the common functionality exhibited by collections and
facilitate data exchange between collections.
2. A small set of implementations that are concrete implementations of the core interfaces, providing
data structures that a program can use.
3. An assortment of algorithms to perform various operations such as, sorting and searching.
• Collections framework is interface based, collections are implemented according to their interface
type, rather than by implementation types. By using the interfaces whenever collections of objects need
to be handled, interoperability and interchangeability are achieved.
• By convention each of the collection implementation classes provide a constructor to create a
collection based on the elements in the Collection object passed as argument. By the same token, Map
implementations provide a constructor that accepts a Map argument. This allows the implementation of
a collection (Collection/Map) to be changed. But Collections and Maps are not interchangeable.
• Interfaces and their implementations in Java 1.2
Collection
|
|__ Set (no dupes, null allowed based on implementation) HashSet
| |
| |__ SortedSet (Ordered Set) TreeSet
|
|__ List (ordered collection, dupes OK) Vector, ArrayList, LinkedList
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.
• 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.
Method Description
public static Set singleton(Object o) Returns an immutable set containing only the specified object
public static List singletonList(Object o) Returns an immutable list containing only the specified object
public static Map singletonMap(Object Returns an immutable map containing only the specified key,
key, Object value) value pair.
public static List nCopies (int n, Object o) 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. Individual indexed bits can be
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.
For example, it is not permssible 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
iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an
undetermined time in the future.
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:
• 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)
Container Description
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.
Window • Top-level window without a title, border or menus.
• 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.
ScrollPane • Can contain a single component. If the component is larger than the scrollpane, it acquires
vertical / horizontal scrollbars as specified in the constructor.
• SCROLLBARS_AS_NEEDED – default, if nothing specified
• SCROLLBARS_ALWAYS
• SCROLLBARS_NEVER
• Top-level containers (Window, Frame and Dialog) cannot be nested. They can contain other containers
and other components.
• GUI components:
Orientation can be
Scrollbar.HORIZONTAL
Scrollbar.VERTICAL
TextField • Extends TextComponent TextField() – empty field Text event
• Single line of edit / display of text. TextField(int ncols) – size
• Scrolled using arrow keys. TextField(String text) – Action event –
• Depending on the font, number of initial text Enter key is
displayable characters can vary. TextField(String text, int pressed.
• But, never changes size once created. ncols) – initial text and size
• Methods from TextComponent:
• String getSelectedText()
• String getText()
• void setEditable(boolean editable)
• void setText(String text)
TextArea • Extends TextComponent TextArea() – empty area Text event
• Multiple lines of edit/display of text. TextArea(int nrows, int
• Scrolled using arrow keys. ncols) – size
• Can use the TextComponent methods TextArea(String text) –
specified above. initial text
• Scroll parameter in last constructor form TextArea(String text, int
could be nrows, int ncols) – initial
TextArea.SCROLLBARS_BOTH, text and size
TextArea.SCROLLBARS_NONE, TextArea(String text, int
TextArea.SCROLLBARS_HORIZONTAL_ONLY nrows, int ncols, int scroll)
TextArea.SCROLLBARS_VERTICAL_ONLY
• 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.
Chapter 11 Layout Managers
• Precise layout functionality is often performed and a repetitive task. By the principles of OOP, it
should be done by classes dedicated to it. These classes are layout managers.
• Platform independence requires that we delegate the positioning and painting to layout managers. Even
then, Java does not guarantee a button will look the same in different platforms.(w/o using Swing)
• Components are added to a container using add method. A layout manager is associated with the
container to handle the positioning and appearance of the components.
• add method is overloaded. Constraints are used differently by different layout managers. Index can be
used to add the component at a particular place. Default is –1 ( i.e. at the end)
Component add(Component comp)
Component add(Component comp, int index)
void add(Component comp, Object constraints)
void add(Component comp, Object constraints, int index)
• setLayout is used to associate a layout manager to a container. Panel class has a constructor that takes a
layout manager. getLayout returns the associated layout manager.
• It is recommended that the layout manager be associated with the container before any component is
added. If we associate the layout manager after the components are added and the container is already
made visible, the components appear as if they have been added by the previous layout manager (if
none was associated before, then the default). Only subsequent operations (such as resizing) on the
container use the new layout manager. But if the container was not made visible before the new layout
is added, the components are re-laid out by the new layout manager.
• Positioning can be done manually by passing null to setLayout.
• Flow Layout Manager
Honors components preferred size.(Doesn’t constraint height or width)
Arranges components in horizontal rows, if there’s not enough space, it creates another row.
If the container is not big enough to show all the components, Flow Layout Manager does not
resize the component, it just displays whatever can be displayed in the space the container has.
Justification (LEFT, RIGHT or CENTER) can be specified in the constructor of layout manager.
Default for applets and panels.
• Grid Layout Manager
Never honors the components’ preferred size
Arranges the components in no of rows/columns specified in the constructor. Divides the space the
container has into equal size cells that form a matrix of rows/columns.
Each component will take up a cell in the order in which it is added (left to right, row by row)
Each component will be of the same size (as the cell)
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, container’s background color is painted in that space.
Each region can display only one component. If another component is added, it hides the earlier
component.
Event Type Event Source Listener Registration and removal Event Listener Interface
methods provided by the source implemented by a listener
ActionEvent Button addActionListener ActionListener
List removeActionListner
MenuItem
TextField
AdjustmentEvent Scrollbar addAdjustmentListener AdjustmentListener
removeAdjustmentListner
ItemEvent Choice addItemListener ItemListener
List removeItemListner
Checkbox
CheckboxMenuItem
TextEvent TextField addTextListener TextListener
TextArea removeTextListner
ComponentEvent Component add ComponentListener ComponentListener
remove ComponentListner
ContainerEvent Container addContainerListener ContainerListener
removeContainerListner
FocusEvent Component addFocusListener FocusListener
removeFocusListner
KeyEvent Component addKeyListener KeyListener
removeKeyListner
addMouseListener MouseListener
removeMouseListner
MouseEvent Component
addMouseMotionListener MouseMotionListener
removeMouseMotionListner
WindowEvent Window addWindowListener WindowListener
removeWindowListner
Event Listener interfaces and their methods:
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.
• 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 doesn’t have this problem.
But with applets always do the initialization in the init method. That’s the normal practice.
• Methods involved in applet’s lifecycle.
Method Description
void init() 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.
void start() Applet context calls this method for the first time after calling init(), and thereafter
every time the applet page is made visible.
void stop() 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.
void destroy() 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.
void paint(Graphics g) Applets normally put all the rendering operations in this method.
• Limitations for Applets:
• Reading, writing or deleting files on local host is not allowed.
• Running other applications from within the applet is prohibited.
• Calling System.exit() to terminate the applet is not allowed.
• Accessing user, file and system information, other than locale-specific information like Java
version, OS name and version, text-encoding standard, file-path and line separators, is prohibited.
• Connecting to hosts other than the one from which the applet was loaded is not permitted.
• Top-level windows that an applet creates have a warning message for applets loaded over the net.
• Some other methods of Applet class
Method Description
URL getDocumentBase() Returns the document URL, i.e. the URL of the HTML file in 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 showStatus(String msg) Applet can request the applet context to display messages in its “status window”.
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
• 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 Character
Byte Streams Purpose
Type Streams
Use these streams to read from and write to memory.
CharArrayReader, ByteArrayInputStream, You create these streams on an existing array and then
CharArrayWriter ByteArrayOutputStream use the read and write methods to read from or write to
the array.
Memory Use StringReader to read characters from a String as it
lives in memory. Use StringWriter to write to a String.
StringReader, StringWriter collects the characters written to it in a
StringBufferInputStream
StringWriter StringBuffer, which can then be converted to a String.
StringBufferInputStream is similar to StringReader,
except that it reads bytes from a StringBuffer.
Implement the input and output components of a pipe.
PipedReader, PipedInputStream,
Pipe Pipes are used to channel the output from one program
PipedWriter PipedOutputStream
(or thread) into the input of another.
FileReader, FileInputStream, Collectively called file streams, these streams are used
File
FileWriter FileOutputStream to read from or write to a file on the native file system.
High Level Filter Streams / Processing streams
• Processing streams perform some sort of operation, such as buffering or character encoding, as they
read and write. Like the data sink streams, java.io often contains pairs of streams: one that performs a
particular operation during reading and another that performs the same operation (or reverses it) during
writing. This table gives java.io's processing streams.
Character
Process Byte Streams Purpose
Streams
Buffer data while reading or writing, thereby
reducing the number of accesses required on
BufferedReader, BufferedInputStream,
Buffering the original data source. Buffered streams are
BufferedWriter BufferedOutputStream
typically more efficient than similar
nonbuffered streams.
Abstract classes, like their parents. They
FilterReader, FilterInputStream,
Filtering define the interface for filter streams, which
FilterWriter FilterOutputStream
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
using either the default character-encoding or
between InputStreamReader,
N/A a character-encoding specified by name.
Bytes and OutputStreamWriter
Similarly, an OutputStreamWriter converts
Characters
characters to bytes using either the default
character-encoding or a character-encoding
specified by name and then writes those bytes
to an OutputStream.
Concatenates multiple input streams into one
Concatenation N/A SequenceInputStream
input stream.
Object ObjectInputStream,
N/A Used to serialize objects.
Serialization ObjectOutputStream
Read or write primitive Java data types in a
DataInputStream,
Data Conversion N/A machine-independent format. Implement
DataOutputStream
DataInput/DataOutput interfaces.
Counting LineNumberReader LineNumberInputStream Keeps track of line numbers 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 in the stream in
Peeking Ahead PushbackReader PushbackInputStream order to decide 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 streams to write to, so you will
Printing PrintWriter PrintStream
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:
abstract int read() throws IOException
int read(char cbuf[]) throws IOException
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.
Both Reader and InputStream are abstract. Subclasses should provide implementation for the read()
method.
• Writer and OutputStream are similarly parallel. Writer defines these methods for writing characters
and arrays of characters:
abstract int write(int c) throws IOException
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
Both Writer and OutputStream are abstract. Subclasses should provide implementation for the
write() method.
DataInputStream(InputStream in)
DataOutputStream(OutputStream out)
BufferedInputStream(InputStream in)
BufferedInputStream(InputStream in, int size)
BufferedOutputStream(OutputStream out)
BufferedOutputStream(OutputStream out, int size)
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)
• 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.
• 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.
Constructor Description
File(File dir, String Creates a File instance that represents the file with the
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 of
String name) 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 getAbsolutePath() Returns the absolute pathname of the file represented by this object.
String getCanonicalPath() Returns the canonical form of this File object's 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 isAbsolute() Tests if the file represented by this File object is an absolute
pathname.
boolean isDirectory() Tests if the file represented by this File object is a 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 object was last
modified.
long length() Returns the length of the file (in bytes) represented by this File
object.
String[] list() Returns a list of the files in the directory specified by this File
object.
String[] list(FilenameFilter) Returns a list of the files in the directory specified by this File that
satisfy the specified filter.
FileNameFilter is an interface that has a method accept().
This list method will call accept for each entry in the list of files
and only returns the files for which accept returns true.
boolean mkdir() Creates a directory whose pathname is specified by this File object.
boolean mkdirs() Creates a directory whose pathname is specified by this File object,
including any necessary parent directories.
boolean renameTo(File) Renames the file specified by this File object to have the pathname
given by the File argument.
• 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
• RAF Constructors
Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read from, and
throws FileNotFoundException, optionally to write to, the file specified by the File argument.
IllegalArgumentException, SecurityException
RandomAccessFile(String name, String mode) Creates a random access file stream to read from, and
throws FileNotFoundException, optionally to write to, a file with the specified name.
IllegalArgumentException, SecurityException
• 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 getFilePointer() throws Returns the offset from the beginning of the file, in bytes, at which the next read
IOException or write occurs.
void seek(long pos) throws Sets the file-pointer offset, measured from the beginning of this file, at which
IOException 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