Java Certification Study Notes
Java Certification Study Notes
Disclaimers No claims are made about the accuracy of this document and no responsibility is taken for any errors. The exam objectives below are quoted, as is from Sun Microsystems web site. This document can be used and distributed as long as the purpose is not commercial. This document has material collected from a lot of resources. I have listed some of the resources here. Im thankful to all those great people. Anything I forgot to mention is not intentional. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Java 1.1 Certification Study Guide by Simon Roberts and Philip Heller. Java 2 Certification Study Guide by Simon Roberts, Philip Heller and Michael Ernst. Java 2 Exam Cram by Bill Brogden A Programmers guide to Java Certification by Khalid Azim Mughal and Rolf Rasmussen Java Language Specification from Sun http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html Java tutorial from Sun - http://java.sun.com/docs/books/tutorial/index.html Java API documentation from Sun - http://java.sun.com/j2se/1.3/docs/api/overview-summary.html Marcus Green - http://www.jchq.net Java Ranch Discussions and Archives - http://www.javaranch.com/ Maha Annas Resource Page - http://www.javaranch.com/maha/ Jyothi's page - http://www.geocities.com/SiliconValley/Network/3693/ Dylan Walshs exam revision page - http://indigo.ie/~dywalsh/certification/index.htm 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]
Section 7 Threads
12. Java has 8 primitive data types. Data Type boolean byte short char int long float double 13. 14. 15. 16. 17. 18. Size (bits) 1 8 16 16 32 64 32 64 Initial Value false 0 0 \u0000 0 0L 0.0F 0.0 Min Value false -128 (-27) -215 \u0000 (0) -231 -263 1.4E-45 4.9E-324 Max Value true 127 (27 1) 215 - 1 \uFFFF (216 1) 231 - 1 263 - 1 3.4028235E38 1.7976931348623157E308
All numeric data types are signed. char is the only unsigned integral type. Object reference variables are initialized to null. Octal literals begin with zero. Hex literals begin with 0X or 0x. Char literals are single quoted characters or unicode values (begin with \u). A number is by default an int literal, a decimal number is by default a double literal. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that its 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 wont compile. Specify else part or initialize the local variable explicitly. Page 5 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
public String testMethod ( int a) { String tmp; if ( a > 0 ) tmp = Positive; 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 arrays 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.
int[] i = new int[2] { 5, 10}; // Wrong int i[5] = { 1, 2, 3, 4, 5}; // Wrong int[] i[] = {{}, new int[] {} }; // Correct int i[][] = { {1,2}, new int[2] }; // Correct int i[] = { 1, 2, 3, 4, } ; // Correct
28. Array indexes start with 0. Index is an int data type. 29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them. 30. Arrays declared even as member variables also need to be allocated memory explicitly.
static int a[]; static int b[] = {1,2,3}; public static void main(String s[]) { System.out.println(a[0]); // Throws a null pointer exception System.out.println(b[0]); // This code runs fine System.out.println(a); // Prints null System.out.println(b); // Prints a string which is returned by toString }
31. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values. 32. If only declared (not constructed), member array variables default to null, but local array variables will not default to null. 33. Java doesnt support multidimensional arrays formally, but it supports arrays of arrays. From the specification - The number of bracket pairs indicates the depth of array nesting. So this can perform as a multidimensional array. (no limit to levels of array nesting) 34. In order to be run by JVM, a class should have a main method with the following signature.
public static void main(String args[]) static public void main(String[] s)
args arrays name is not important. args[0] is the first argument. args.length gives no. of arguments. main method can be overloaded. main method can be final. A class with a different main signature or w/o main method will compile. But throws a runtime error. A class without a main method can be run by JVM, if its ancestor class has a main method. (main is just a method and is inherited) Page 6 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
In the descendents this method can be protected or public. Descendents can restrict the exception list that can be thrown by this method. finalize is called only once for an object. If any exception is thrown in finalize, the object is still eligible for garbage collection (at the discretion of gc) gc keeps track of unreachable objects and garbage-collects them, but an unreachable object can become reachable again by letting know other objects of its existence from its finalize method (when called by gc). This resurrection can be done only once, since finalize is called only one for an object. finalize can be called explicitly, but it does not garbage collect the object. finalize can be overloaded, but only the method with original finalize signature will be called by gc. 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 doesnt enforce this check. System.runFinalization can be used to run the finalizers (which have not been executed before) for the objects eligible for garbage collection. The following table specifies the color coding of javadoc standard. (May be not applicable to 1.2) Member Instance method Static method Final variable Constructor Color Red Green Blue Yellow
Implicit narrowing conversion is done, when applied to byte, short or char. 1.2 Unary minus and unary plus + + has no effect than to stress positivity. - negates an expressions value. (2s complement for integral expressions) 1.3 Negation ! Inverts the value of a boolean expression. 1.4 Complement ~ Inverts the bit pattern of an integral expression. (1s complement 0s to 1s and 1s to 0s) Cannot be applied to non-integral types. 1.5 Cast () Persuades compiler to allow certain assignments. Extensive checking is done at compile and runtime to ensure type-safety. Arithmetic operators - *, /, %, +, Can be applied to all numeric types. Can be applied to only the numeric types, except + it can be applied to Strings as well. All arithmetic operations are done at least with int. (If types are smaller, promotion happens. Result will be of a type at least as wide as the wide type of operands) Accuracy is lost silently when arithmetic overflow/error occurs. Result is a nonsense value. Integer division by zero throws an exception. % - reduce the magnitude of LHS by the magnitude of RHS. (continuous subtraction) % - sign of the result entirely determined by sign of LHS 5 % 0 throws an ArithmeticException. Floating point calculations can produce NaN (square root of a negative no) or Infinity ( division by zero). Float and Double wrapper classes have named constants for NaN and infinities. NaNs are non-ordinal for comparisons. x == Float.NaN wont work. Use Float.IsNaN(x) But equals method on wrapper objects(Double or Float) with NaN values compares Nans correctly. Infinities are ordinal. X == Double.POSITIVE_INFINITY will give expected result. + also performs String concatenation (when any operand in an expression is a String). The language itself overloads this operator. toString method of non-String object operands are called to perform concatenation. In case of primitives, a wrapper object is created with the primitive value and toString method of that object is called. (Vel + 3 will work.) Be aware of associativity when multiple operands are involved. System.out.println( 1 + 2 + 3 ); // Prints 33 System.out.println( 1 + 2 + 3 ); // Prints 123 Shift operators - <<, >>, >>> << performs a signed left shift. 0 bits are brought in from the right. Sign bit (MSB) is preserved. Value becomes old value * 2 ^ x where x is no of bits shifted. Page 8 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
2.
3.
5.
6.
7.
8.
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.
element
the 4th
Type of Operators Postfix operators Prefix Unary operators Object creation and cast Multiplication/Division/Modulus Addition/Subtraction Shift Relational Equality Bit-wise/Boolean AND Bit-wise/Boolean XOR Bit-wise/Boolean OR Logical AND (Short-circuit or Conditional) Logical OR (Short-circuit or Conditional) Ternary Assignment
Operators [] . (parameters) ++ -++ -- + - ~ ! new (type) */% +>> >>> << < <= > >= instanceof == != & ^ | && || ?: = += -= *= /= %= <<= >>= >>>= &= ^= |=
Associativity Left to Right Right to Left Right to Left Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Left to Right Right to Left Right to Left
4.
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. abstract Can be applied to classes and methods. For deferring implementation to sub-classes. Opposite of final, final cant be sub-classed, abstract must be sub-classed. A class should be declared abstract, 1. if it has any abstract methods. 2. if it doesnt provide implementation to any of the abstract methods it inherited Page 12 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
3.
5.
class Parent { static int x = 100; public static void doStuff() { System.out.println("In Parent..doStuff"); System.out.println(x); } } class Child extends Parent { static int x = 200; public static void doStuff() { System.out.println("In Child..doStuff"); System.out.println(x); } }
6.
native
Can be applied to methods only. (static methods also) Written in a non-Java language, compiled for a single machine target type. Page 13 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
7.
8.
9.
Modifier
public protected (friendly) No access modifier private final abstract static native transient synchronized
Y N Y N Y Y N N N N
Y Y Y Y Y N Y N Y N
Y Y Y Y Y Y Y Y N Y
Y Y Y Y N N N N N N
N N N N N N Y (static initializer) N N Y (part of method, also need to specify an object on which a lock should be obtained) N
volatile
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. Page 15 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
7.
8.
Here is the figure of allowable primitive conversion. byte short int long float double char Casting of Primitives 9. Needed with narrowing conversions. Use with care radical information loss. Also can be used with widening conversions, to improve the clarity of the code. 10. Can cast any non-boolean type to another non-boolean type. 11. Cannot cast a boolean or to a boolean type. Conversion of Object references 12. Three types of reference variables to denote objects - class, interface or array type. 13. Two kinds of objects can be created class or array. 14. Two types of conversion assignment and method call. 15. Permitted if the direction of the conversion is up the inheritance hierarchy. Means that types can be assigned/substituted to only super-types super-classes or interfaces. Not the other way around, explicit casting is needed for that. 16. Interfaces can be used as types when declaring variables, so they participate in the object reference conversion. But we cannot instantiate an interface, since it is abstract and doesnt provide any implementation. These variables can be used to hold objects of classes that implement the interface. The reason for having interfaces as types may be, I think, several unrelated classes may implement the same interface and if theres 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. Casting of Object references 19. Allows super-types to be assigned to subtypes. Extensive checks done both at compile and runtime. At compile time, class of the object may not be known, so at runtime if checks fail, a ClassCastException is thrown. 20. Cast operator, instanceof operator and the == operator behave the same way in allowing references to be the operands of them. You cannot cast or apply instanceof or compare unrelated references, sibling references or any incompatible references.
Compile-time Rules When old and new types are classes, one class must be the sub-class of the other. When old and new types are arrays, both must contain reference types and it must be legal to cast between those types (primitive arrays cannot be cast, conversion possible only between same type of primitive arrays). We can always cast between an interface and a non-final object. Run-time rules If new type is a class, the class of the expression being converted must be new type or extend new type. If new type is an interface, the class of the expression being converted must implement the interface. An Object reference can be converted to: (java.lang.Object) an Object reference a Cloneable interface reference, with casting, with runtime check any class reference, with casting, with runtime check any array referenece, with casting, with runtime check any interface reference, with casting, with runtime check A Class type reference can be converted to: any super-class type reference, (including Object) any sub-class type reference, with casting, with runtime check an interface reference, if the class implements that interface any interface reference, with casting, with runtime check (except if the class is final and doesnt implement the interface) An Interface reference can be converted to: an Object reference a super-interface reference any interface/class reference with casting, with runtime check (except if the class is final and doesnt implement the interface) A Primitive Array reference can be converted to: an Object reference a Cloneable interface reference a primitive array reference of the same type An Object Array reference can be converted to: an Object reference a Cloneable interface reference a super-class Array reference, including an Object Array reference any sub-class Array reference with casting, with runtime check
1.
2.
3.
We need to place a break statement in each case block to prevent the execution to fall through other case blocks. But this is not a part of switch statement and not enforced by the compiler. We can have multiple case statements execute the same code. Just list them one by one. default case can be placed anywhere. Itll be executed only if none of the case values match. switch can be nested. Nested case labels are independent, dont clash with outer case labels. Empty switch construct is a valid construct. But any statement within the switch block should come under a case label or the default case label. Branching statements break statement can be used with any kind of loop or a switch statement or just a labeled block. continue statement can be used with only a loop (any kind of loop). Loops can have labels. We can use break and continue statements to branch out of multiple levels of nested loops using labels. Names of the labels follow the same rules as the name of the variables.(Identifiers) Labels can have the same name, as long as they dont enclose one another. Page 18 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
4.
Here is the exception hierarchy. Object | | Throwable | | | | | | | Error | | Exception-->ClassNotFoundException, ClassNotSupportedException, IllegalAccessException, InstantiationException, IterruptedException, NoSuchMethodException, RuntimeException, AWTException, IOException 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.
Methods can be static or non-static. Since the methods are independent, it doesnt matter. But if two methods have the same signature, declaring one as static and another as non-static does not provide a valid overload. Its a compile time error.
Variables can also be overridden, its 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 its already resolved at compile time based on the reference variable type. Only methods are resolved at run-time.
public class Shadow { public static void main(String s[]) { S1 s1 = new S1(); S2 s2 = new S2(); 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.s); // prints S1, not S2 // since variable is resolved System.out.println(s1.getS()); // prints S2 // since method } }
at compile time
class S2 extends S1{ public String s = "S2"; public String getS() { return s; }
In the above code, if we didnt have the overriding getS() method in the sub-class and if we call the method from sub-class reference variable, the method will return only the super-class member variable value. For explanation, see the following point. Also, methods access variables only in context of the class of the object they belong to. If a sub-class method calls explicitly a super class method, the super class method always will access the super-class variable. Super class methods will not access the shadowing variables declared in subclasses because they dont know about them. (When an object is created, instances of all its super-classes are also created.) But the method accessed will be again subject to dynamic lookup. It is always decided at runtime which implementation is called. (Only static methods are resolved at compile-time)
public class Shadow2 { String s = "main"; public static void main(String s[]) { S2 s2 = new S2(); s2.display(); // Produces an
output S1, S2 // prints S1 // 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 variables real type at any time since when it allocates memory for an object, it also marks the type with it. Objects always know who they are. This is the basis of instanceof operator. Sub-classes can use super keyword to access the shadowed variables in 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-superclass, the compiler binds the super-super-class variable. But this technique is not possible with methods since methods are resolved always at runtime, and the method gets called depends on the type of object, not the type of reference variable. So it is not at all possible to access a method in a super-super-class from a subclass.
public class ShadowTest { public static void main(String s[]){ new STChild().demo(); } } class STGrandParent { double wealth = 50000.00; public double getWealth() { System.out.println("GrandParent-" + wealth); return wealth; } } class STParent extends STGrandParent { double wealth = 100000.00; public double getWealth() { System.out.println("Parent-" + wealth); return wealth; } } class STChild extends STParent { double wealth = 200000.00; public double getWealth() { System.out.println("Child-" + wealth); return wealth; } public void demo() { getWealth(); // Calls Child method super.getWealth(); // Calls Parent method // Compiler error, GrandParent method cannot be accessed //super.super.getWealth(); // Calls Child method, due to dynamic method lookup ((STParent)this).getWealth();
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.
public class PrivateTest { public static void main(String s[]){ new PTSuper().hi(); // Prints always Super new PTSub().hi(); // Prints Super when subclass doesn't have hi method // Prints Sub when subclass has hi method PTSuper sup; sup = new PTSub(); sup.hi(); // Prints Super when subclass doesn't have hi method // Prints Sub when subclass has hi method } } 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"); } } class PTSub extends PTSuper { public void hi() { // This method overrides super-class hi, calls subclass hello try { hello(); } catch(Exception e) {} } 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[]) {
class PolyA { private int f() { return 0; } public int g() { return 3; } } class PolyB extends PolyA { private int f() { return 1; } public int g() { return f(); } } class PolyC extends PolyB { public int f() { return 2; } }
Constructors and Sub-classing Constructors are not inherited as normal methods, they have to be defined in the class itself. If you define no constructors at all, then the compiler provides a default constructor with no arguments. Even if, you define one constructor, this default is not provided. We cant compile a sub-class if the immediate super-class doesnt have a no argument default constructor, and sub-class constructors are not calling super or this explicitly (and expect the compiler to insert an implicit super() call ) A constructor can call other overloaded constructors by this (arguments). If you use this, it must be the first statement in the constructor. This construct can be used only from within a constructor. A constructor cant call the same constructor from within. Compiler will say recursive constructor invocation A constructor can call the parent class constructor explicitly by using super (arguments). If you do this, it must be first the statement in the constructor. This construct can be used only from within a constructor. Obviously, we cant use both this and super in the same constructor. If compiler sees a this or super, it wont insert a default call to super(). Constructors cant have a return type. A method with a class name, but with a return type is not considered a constructor, but just a method by compiler. Expect trick questions using this. Constructor body can have an empty return statement. Though void cannot be specified with the constructor signature, empty return statement is acceptable. Only modifiers that a constructor can have are the accessibility modifiers. Constructors cannot be overridden, since they are not inherited. Initializers are used in initialization of objects and classes and to define constants in interfaces. These initializers are : 1. Static and Instance variable initializer expressions. Literals and method calls to initialize variables. Static variables can be initialized only by static method calls. Cannot pass on the checked exceptions. Must catch and handle them. 2. Static initializer blocks. Used to initialize static variables and load native libraries. Cannot pass on the checked exceptions. Must catch and handle them. 3. Instance initializer blocks. Used to factor out code that is common to all the constructors. Page 25 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
// //
// Example 2
public class InnerTest2 { public static void main(String s[]) { new OuterClass().doSomething(10, 20); // This is legal // OuterClass.InnerClass ic = new OuterClass().new InnerClass(); // ic.doSomething(); // Compiler error, local inner classes cannot be accessed from outside // OuterClass.LocalInnerClass lic = new OuterClass().new LocalInnerClass(); // lic.doSomething(); new OuterClass().doAnonymous(); } } class OuterClass { final int a = 100; private String secret = "Nothing serious"; public void doSomething(int arg, final int fa) { final int x = 100; int y = 200; 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); // Compiler error, forward reference of local inner class // new LocalInnerClass().doSomething(); abstract class AncestorLocalInnerClass { } // inner class can be abstract final class LocalInnerClass extends AncestorLocalInnerClass { // can be final public void doSomething() { System.out.println(this.getClass() + " - in doSomething"); System.out.print("a = " + a ); System.out.print(" secret = " + secret); System.out.print(" arg = " + arg); // Compiler error, accessing non-final argument System.out.print(" fa = " + fa); System.out.println(" x = " + x); System.out.println(" y = " + y); // Compiler error, accessing non-final variable } } new InnerClass().doSomething(); // forward reference fine for member inner class new LocalInnerClass().doSomething(); }
// //
abstract class AncestorInnerClass { } interface InnerInterface { final int someConstant = 999;} // inner interface class InnerClass extends AncestorInnerClass implements InnerInterface { public void doSomething() { System.out.println(this.getClass() + " - in doSomething"); System.out.println("a = " + a + " secret = " + secret + " someConstant = " + someConstant); } } public void doAnonymous() { // Anonymous class implementing the inner interface System.out.println((new InnerInterface() { }).someConstant); // Anonymous class extending the inner class ( new InnerClass() { public void doSomething() { secret = "secret is changed"; super.doSomething(); } } ).doSomething(); } }
Entity Package level class Top level nested class (static) Non static inner class Local class (nonstatic) Local class (static) Anonymous class (non-static) Anonymous class (static) Package level interface Top level nested interface (static)
Declaration Context As package member As static class member As non-static class member In block with non-static context In block with static context In block with non-static context In block with static context As package member As static class member
Accessibility Modifiers Public or default All All None None None None Public or default All
Direct Access to enclosing context N/A Static members in enclosing context All members in enclosing context All members in enclosing context + local final variables Static members in enclosing context + local final variables All members in enclosing context + local final variables Static members in enclosing context + local final variables N/A Static members in enclosing context
Defines static or non-static members Both static and nonstatic Both static and nonstatic Only non-static Only non-static Only non-static Only non-static Only non-static Static variables and non-static method prototypes Static variables and non-static method prototypes
2.
1.
Time-sliced or Round Robin Scheduling Page 33 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
1.
2.
3.
4.
5.
Blocked Thread is waiting to get a lock on the monitor. (or waiting for a blocking i/o method) Caused by the thread tried to execute some synchronized code. (or a blocking i/o method) Can move to ready only when the lock is available. ( or the i/o operation is complete)
Points for complex models: 1. Always check monitors state in a while loop, rather than in an if statement. 2. Always call notifyAll, instead of notify. Class locks control the static methods. wait and sleep must be enclosed in a try/catch for InterruptedException. A single thread can obtain multiple locks on multiple objects (or on the same object) Page 35 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Method boolean equals(Object o) final native void wait() final native void notify() final native void notifyAll() native int hashcode() protected Object clone() throws CloneNotSupportedException CloneNotSupportedException is a checked Exception
Math class is final, cannot be sub-classed. Math constructor is private, cannot be instantiated. All constants and methods are public and static, just access using class name. Two constants PI and E are specified. Methods that implement Trigonometry functions are native. All Math trig functions take angle input in radians. Angle degrees * PI / 180 = Angle radians Order of floating/double values: -Infinity --> Negative Numbers/Fractions --> -0.0 --> +0.0 --> Positive Numbers/Fractions --> Infinity abs int, long, float, double versions available floor greatest integer smaller than this number (look below towards the floor) ceil smallest integer greater than this number (look above towards the ceiling) For floor and ceil functions, if the argument is NaN or infinity or positive zero or negative zero or already a value equal to a mathematical integer, the result is the same as the argument. For ceil, if the argument is less than zero but greater than 1.0, then the result is a negative zero Page 37 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
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 Map (key-value pairs, null allowed based on implementation) HashTable, HashMap | |__ SortedMap (Ordered Map) TreeMap Interface Collection Set SortedSet List Map SortedMap Description A basic interface that defines the operations that all the classes that maintain collections of objects typically implement. Extends Collection, sets that maintain unique elements. Set interface is defined in terms of the equals operation Extends Set, maintain the elements in a sorted order Extends Collection, maintain elements in a sequential order, duplicates allowed. A basic interface that defines operations that classes that represent mappings of keys to values typically implement Extends Map for maps that maintain their mappings in key order.
Classes that implement the interfaces use different storage mechanisms. 1. Arrays Indexed access is faster. Makes insertion, deletion and growing the store more difficult. 2. Linked List Supports insertion, deletion and growing the store. But indexed access is slower. 3. Tree Supports insertion, deletion and growing the store. Indexed access is slower. But searching is faster. 4. Hashing Supports insertion, deletion and growing the store. Indexed access is slower. But searching is faster. Page 40 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
SortedMap
TreeMap
Some of the operations in the collection interfaces are optional, meaning that the implementing class may choose not to provide a proper implementation of such an operation. In such a case, an UnsupportedOperationException is thrown when that operation is invoked. Interface Basic Operations Methods int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); Object[] toArray(); Object[] toArray(Object a[]); Iterator iterator(); Iterator is an interface which has these methods. boolean hasNext(); Object next(); void remove(); No new methods defined. Element Access by Index Element Search Object get(int index); Object set(int index, Object element); void add(int index, Object element); Object remove(int index); boolean addAll(int index, Collection c); int indexOf(Object o); int lastIndexOf(Object o); Description Used to query a collection about its contents, and add/remove elements. The add() and remove() methods return true if the collection was modified as a result of the operation. The contains() method checks for membership. Perform on a collection as a single unit. Operations are equivalent of set logic on arbitrary collections (not just sets). The addAll(), removeAll(), clear() and retainAll() methods are destructive. These methods combined with Arrays.asList() method provide the bridge between arrays and collections. Returns an iterator, to iterate the collection. The remove() method is the only recommended way to remove elements from a collection during the iteration. The add() method returns false, if the element is already in the Set. No exceptions are thrown. First index is 0, last index is size() 1. An illegal index throws IndexOutOfBoundsException. If the element is not found, return 1.
Set List
Basic Operations
Map
Bulk Operations
Range View Operations SortedSet Min-Max Points Comparator Access Range View Operations SortedMap Min-Max Points Comparator Access
Sorting in SortedSets and SortedMaps can be implemented in two ways. 1. Objects can specify their natural order by implementing Comparable interface. Many if the standard classes in Java API, such as wrapper classes, String, Date and File implement this interface. This interface defines a single method: int compareTo(Object o) returns negative, zero, positive if the current object is less than, equal to or greater than the specified object. In this case a natural comparator queries objects implementing Comparable about their natural order. Objects implementing this interface can be used: As elements in a sorted set. Page 42 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
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 Page 43 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Location
Container class extends Component. This class defines methods for nesting components in a container. Component add(Component comp) Component add(Component comp, int index) void add(Component comp, Object constraints) void add(Component comp, Object constraints, int index) void remove(int index) void remove(Component comp) void removeAll() The following are the containers: Container Panel Description 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. 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. 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 Page 45 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Applet
Window
Dialog
ScrollPane
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. Top-level window (optionally user-resizable and movable) with a title-bar. Doesnt have icons or menus. Can be made modal. A parent frame needs to be specified to create a Dialog. Default layout is Border layout. 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: Component Button Canvas Description A button with a textual label. No default appearance. Can be sub-classed to create custom drawing areas. Toggling check box. Default initial state is false. getState(), setState(boolean state) - methods Can be grouped with a CheckboxGroup to provide radio behavior. Checkboxgroup is not a subclass of Component. Checkboxgroup provides these methods: getSelectedCheckbox and setSelectedCheckbox(Checkbox new) A pull-down list Can be populated by repeatedly calling addItem(String item) method. Only the current choice is visible. Subclass of Dialog Open or Save file dialog, modal Dialog automatically removed, after user selects the file or hits cancel. getFile(), getDirectory() methods can be used to get information about the selected file. Constructors new Button(Apply) Events Action event. Mouse, MouseMotion, Key events. Item event
Checkbox
Checkbox(String label) Checkbox(String label, boolean initialstate) Checkbox(String label, CheckBoxGroup group)
Choice
Item event
FileDialog
FileDialog(Frame parent, String title, int mode) Mode can be FileDialog.LOAD or FileDialog.SAVE
List
Scrollbar
Scrollbar() a vertical scrollbar. Scrollbar(int orientation) Scrollbar(int orientation, int initialvalue, int slidersize, int minvalue, int maxvalue) Orientation can be Scrollbar.HORIZONTAL Scrollbar.VERTICAL TextField() empty field TextField(int ncols) size TextField(String text) initial text TextField(String text, int ncols) initial text and size
Adjustment event
TextField
TextArea
Extends TextComponent Single line of edit / display of text. Scrolled using arrow keys. Depending on the font, number of displayable characters can vary. But, never changes size once created. Methods from TextComponent: String getSelectedText() String getText() void setEditable(boolean editable) void setText(String text) Extends TextComponent Multiple lines of edit/display of text. Scrolled using arrow keys. Can use the TextComponent methods specified above. Scroll parameter in last constructor form could be
TextArea.SCROLLBARS_BOTH, TextArea.SCROLLBARS_NONE, TextArea.SCROLLBARS_HORIZONTAL_ONLY TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea() empty area TextArea(int nrows, int ncols) size TextArea(String text) initial text TextArea(String text, int nrows, int ncols) initial text and size TextArea(String text, int nrows, int ncols, int scroll)
Text event
Pull-down menus are accessed via a menu bar, which can appear only on Frames. Page 47 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Specify Location
Dimension
Where a component should be placed within its display area. Constants defined in GridBagConstraints: CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST
0 for both, meaning that the area allocated for the component will not grow beyond the preferred size. GridBagConstraints.CENTER
Padding
Insets
Description Lays out the components in row-major order. Rows growing from left to right, top to bottom. Lays out the components in a specified rectangular grid, from left to right in each row and filling rows from top to bottom. Up to 5 components can be placed in particular locations: north, south, east, west and center. Components are handled as a stack of indexed cards. Shows only one at a time. Customizable and flexible layout manager that lays out the components in a rectangular grid.
Constructors FlowLayout() - center aligned, 5 pixels gap both horizontally and vertically FlowLayout(int alignment) FlowLayout(int alignment, int hgap, int vgap) GridLayout() equivalent to GridLayout(1,0) GridLayout(int rows, int columns)
GridLayout
BorderLayout
CardLayout
GridbagLayout
GridbagLayout()
None
ADJUSTMENT_VALUE_CHANGED ITEM_STATE_CHANGED
TextEvent
TEXT_VALUE_CHANGED
Methods defined in the events to get the information about them. Event Class Method Description String getActionCommand Returns the command name associated with this action int getModifiers Returns the sum of modifier constants corresponding to the keyboard ActionEvent modifiers held down during this action. SHIFT_MASK, ALT_MASK, CTRL_MASK, META_MASK AdjustmentEvent int getvalue Returns the current value designated by the adjustable component ItemEvent Object getItem Returns the object that was selected or deselected Label of the checkbox
PaintEvent
All components
WindowEvent
All windows
Methods defined in the events to get the information about them. Event Class Method Description ComponentEvent Component getComponent Returns a reference to the same object as getSource, but the returned reference is of type Component. Container getContainer Returns the container where this event originated. ContainerEvent Component getChild Returns the child component that was added or removed in this event FocusEvent boolean isTemporary Determines whether the loss of focus is permanent or temporary long getWhen Returns the time the event has taken place. int getModifiers Returns the modifiers flag for this event. InputEvent void consume Consumes this event so that it will not be processed in the default manner by the source that originated it. int getKeyCode For KEY_PRESSED or KEY_RELEASED events, this method can be used to get the integer key-code associated with the key. Keycodes are defined as constants is KeyEvent class. KeyEvent char getKeyChar For KEY_TYPED events, this method returns the Unicode character that was generated by the keystroke. MouseEvent int getX Return the position of the mouse within the originated component at the time the event took place int getY Point getPoint Page 53 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
WindowEvent
Event Listeners Each listener interface extends java.util.EventListener interface. There are 11 listener interfaces corresponding to particular events. Any class that wants to handle an event should implement the corresponding interface. Listener interface methods are passed the event object that has all the information about the event occurred. Then the listener classes should be registered with the component that is the source/originator of the event by calling the addXXXListener method on the component. Listeners are unregistered by calling removeXXXListener method on the component. A component may have multiple listeners for any event type. A component can be its own listener if it implements the necessary interface. Or it can handle its events by implementing the processEvent method. (This is discussed in explicit event enabling section) All registered listeners with the component are notified (by invoking the methods passing the event object). But the order of notification is not guaranteed (even if the same component is registered as its own listener). Also the notification is not guaranteed to occur on the same thread. Listeners should take cautions not to corrupt the shared data. Access to any data shared between the listeners should be synchronized. Same listener object can implement multiple listener interfaces. Event listeners are usually implemented as anonymous classes. Event Type ActionEvent Event Source Button List MenuItem TextField Scrollbar Choice List Checkbox CheckboxMenuItem TextField TextArea Component Container Component Component Listener Registration and removal methods provided by the source addActionListener removeActionListner Event Listener Interface implemented by a listener ActionListener
AdjustmentEvent ItemEvent
addAdjustmentListener removeAdjustmentListner addItemListener removeItemListner addTextListener removeTextListner add ComponentListener remove ComponentListner addContainerListener removeContainerListner addFocusListener removeFocusListner addKeyListener removeKeyListner addMouseListener removeMouseListner
AdjustmentListener ItemListener
MouseEvent
Component
addMouseMotionListener removeMouseMotionListner
Event Listener interfaces and their methods: Event Listener Interface ActionListener AdjustmentListener ItemListener TextListener ComponentListener Event Listener Methods void actionPerformed(ActionEvent evt) void adjustmentValueChanged(AdjustmentEvent evt) void itemStateChanged(ItemEvent evt) void textValueChanged(TextEvent evt) void componentHidden(ComponentEvent evt) void componentShown(ComponentEvent evt) void componentMoved(ComponentEvent evt) void componentResized(ComponentEvent evt) void componentAdded(ContainerEvent evt) void componentRemoved(ContainerEvent evt) void focusGained(FocusEvent evt) void focusLost(FocusEvent evt) void keyPressed(KeyEvent evt) void keyReleased(KeyEvent evt) void keyTyped(KeyEvent evt) void mouseClicked(MouseEvent evt) void mouseReleased(MouseEvent evt) void mousePressed(MouseEvent evt) void mouseEntered(MouseEvent evt) void mouseExited(MouseEvent evt) void mouseDragged(MouseEvent evt) void mouseMoved(MouseEvent evt) void windowActivated(WindowEvent evt) void windowDeactivated(WindowEvent evt) void windowIconified(WindowEvent evt) void windowDeiconified(WindowEvent evt) void windowClosing(WindowEvent evt) void windowClosed(WindowEvent evt) void windowOpened(WindowEvent evt)
MouseMotionListener WindowListener
Event Adapters Event Adapters are convenient classes implementing the event listener interfaces. They provide empty bodies for the listener interface methods, so we can implement 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. Explicit Event Enabling How events are produced and handled? Page 55 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Steps for handling events using listeners or by the same component Delegating to listeners Create a listener class, either by implementing an event listener interface or extending an event adapter class. Create an instance of the component Create an instance of the listener class Call addXXXListener on the component passing the listener object. (This step automatically enables the processing of this type of event. Default behavior of processEvent method in the component is to delegate the processing to processXXXEvent and that method will invoke appropriate listener class methods.) Handling own events (explicit enabling) Create a subclass of a component Call enableEvents(XXX_EVENT_MASK) in the constructor. Provide processXXXEvent and/or processEvent in the subclass component. If also want to notify the listeners, call parent method. Create an instance of the subclass component
1. 2. 3. 4.
1. 2. 3. 4.
Between <APPLET> and </APPLET>, PARAM tags can be specified. These are used to pass parameters from HTML page to the applet. <PARAM NAME = name VALUE = value> Applets call getParameter(name) to get the parameter. The name is not case sensitive here. The value returned by getParameter is case sensitive, it is returned as defined in the HTML page. If not defined, getParameter returns null. Text specified between <APPLET> and </APPLET> is displayed by completely applet ignorant browsers, who cannot understand even the <APPLET> tag. If the applet class has only non-default constructors, applet viewer throws runtime errors while loading the applet since the default constructor is not provided by the JVM. But IE doesnt have this problem. But with applets always do the initialization in the init method. Thats the normal practice. Methods involved in applets lifecycle. Method Description 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. Page 58 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
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 Low Level Streams/Data sink streams read from or write to specialized data sinks such as strings, files, or pipes. Typically, for each reader or input stream intended to read from a specific kind of input source, java.io contains a parallel writer or output stream that can create it. The following table gives java.io's data sink streams. Sink Type Character Streams CharArrayReader, CharArrayWriter Memory StringReader, StringWriter Byte Streams Purpose
Pipe File
Use these streams to read from and write to memory. ByteArrayInputStream, You create these streams on an existing array and then ByteArrayOutputStream use the read and write methods to read from or write to the array. Use StringReader to read characters from a String as it lives in memory. Use StringWriter to write to a String. StringWriter collects the characters written to it in a StringBufferInputStream 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. PipedInputStream, Pipes are used to channel the output from one program PipedOutputStream (or thread) into the input of another. FileInputStream, Collectively called file streams, these streams are used 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. Process Character Streams BufferedReader, BufferedWriter FilterReader, FilterWriter Byte Streams BufferedInputStream, BufferedOutputStream FilterInputStream, FilterOutputStream Purpose Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams. Abstract classes, like their parents. They define the interface for filter streams, 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 using either the default character-encoding or a character-encoding specified by 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. Concatenates multiple input streams into one input stream. Used to serialize objects. Read or write primitive Java data types in a machine-independent format. Implement DataInput/DataOutput interfaces. 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 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 often see other writable streams wrapped in one of these.
Buffering
Filtering
N/A N/A
Peeking Ahead
PushbackReader
PushbackInputStream
Printing
PrintWriter
PrintStream
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. Page 63 of 65 Last Modified on 03/06/1218:16 A3/P3 2000 Velmurugan Periasamy ([email protected])
Constructor RandomAccessFile(File file, String mode) throws FileNotFoundException, IllegalArgumentException, SecurityException RandomAccessFile(String name, String mode) throws FileNotFoundException, 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. Some RAF methods Description Returns the offset from the beginning of the file, in bytes, at which the next read or write occurs. Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs. The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change the file length. The file length will change only by writing after the offset has been set beyond the end of the file. Returns the length of this file, measured in bytes.
Method long getFilePointer() throws IOException void seek(long pos) throws IOException