Wednesday, August 31, 2005

SCJP study notes:Chapter 8 java.lang package

Originally written by Velmurugan Periasamy. Copyright belongs to him.

Chapter 8 java.lang package

· 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()

final native void notify()

final native void notifyAll()

Thread control. Two other versions of wait() accept timeout parameters and may throw InterruptedException.

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 CloneNotSupportedException

CloneNotSupportedException is a checked Exception

Creates a new object of the same class as this object. It then initializes each of the new object's fields by assigning it the same value as the corresponding field in this object. No constructor is called.

The clone method of class Object will only clone an object whose class indicates that it is 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

Throwable

Called by the garbage collector on an object when garbage collection determines that there 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.

· 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

· random – returns a double between 0.0(including) and 1.0(excluding)

· round returns a long for double, returns an int for float. (closest int or long value to the argument)

The result is rounded to an integer by adding ½ , taking the floor of the result, and casting the result to type int / long.

(int)Math.floor(a + 0.5f)

(long)Math.floor(a + 0.5d)

· double rint(double) returns closest double equivalent to a mathematical integer. If two values are equal, it returns the even integer value. rint(2.7) is 3, rint(2.5) is 2.

· Math.min(-0.0, +0.0) returns –0.0, Math.max(-0.0, +0.0) returns 0.0, -0.0 == +0.0 returns true.

· For a NaN or a negative argument, sqrt returns a NaN.

· Every primitive type has a wrapper class (some names are different – Integer, Boolean, Character)

· Wrapper class objects are immutable.

· All Wrapper classes are final.

· All wrapper classes, except Character, have a constructor accepting string. A Boolean object, created by passing a string, will have a value of false for any input other than “true” (case 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.

· Strings are immutable.

· They can be created from a literal, a byte array, a char array or a string buffer.

· Literals are taken from pool (for optimization), so == will return true, if two strings are pointing to the same literal.

· Anonymous String objects (literals) may have been optimized even across classes.

· A String created by new operator is always a different new object, even if it’s created from a literal.

· But a String can specify that its contents should be placed in a pool of unique strings for possible reuse, by calling intern() method. In programs that do a lot of String comparisons, ensuring that all Strings are in the pool, allows to use == comparison rather than the equals() method, which is slower.

· All string operations (concat, trim, replace, substring etc) construct and return new strings.

· toUpperCase and toLowerCase will return the same string if no case conversion was needed.

· equals takes an object (String class also has a version of equals that accepts a String), equalsIgnoreCase takes a string.

· Passing null to indexOf or lastIndexOf will throw NullPointerException, passing empty string returns 0, passing a string that’s not in the target string returns –1.

· trim method removes all leading and trailing white-space from a String and returns a new String. White-space means, all characters with value less than or equal to the space character – ‘\u0020’.

· String class is final.

· + and += operators are overloaded for Strings.

· reverse, append, insert are not String methods.

· String Buffers are mutable strings.

· StringBuffer is a final class.

· They can be created empty, from a string or with a capacity. An empty StringBuffer is created with 16-character capacity. A StringBuffer created from a String has the capacity of the length of String + 16. StringBuffers created with the specified capacity has the exact capacity specified. Since they can grow dynamically in size without bounds, capacity doesn’t have much effect.

· append, insert, setCharAt, reverse are used to manipulate the string buffer.

· setLength changes the length, if the current content is larger than specified length, it’s truncated. If it is smaller than the specified length, nulls are padded. This method doesn’t affect the capacity.

· equals on StringBuffer does a shallow comparison. (same like ==) Will return true only if the objects are same. Don’t use it to test content equality

· trim is not a StringBuffer method.

· There is no relationship between String and StringBuffer. Both extend Object class.

· String context means, ‘+’ operator appearing with one String operand. String concatenation cannot be applied to StringBuffers.

· A new String buffer is created.

· All operands are appended (by calling toString method, if needed)

· Finally a string is returned by calling toString on the String Buffer.

· String concatenation process will add a string with the value of “null”, if an object reference is null and that object is appearing in a concatenation expression by itself. But if we try to access its members or methods, a NullPointerException is thrown. The same is true for arrays, array name is replaced with null, but trying to index it when it’s null throws a NullPointerException.

2 Comments:

Blogger Krishna said...

350+ SCJP 1.5 Mock Exams and Articles:
SCJP 1.5 Mock Exams

8:20 AM  
Blogger kumar said...

Great publish, very useful information. I really appreciate this post. You must continue your writing. I'm confident, you have a huge readers' base already.Thanks for sharing the valuable post.
Engineering Colleges, Mechanical Engineering Colleges in Chennai

11:59 PM  

Post a Comment

<< Home