Translate

Friday, November 9, 2012

FUNDAMENTAL CLASSES IN java.lang.package


Introduction

The most commonly used and general purpose classes which are required for any java program are grouped into a package which is nothing but a “java.lang.package”. All the classes and interfaces which are available in this package are by default available to any java
program. There is no need to import this class.

Object Class

The most common general methods which can be applicable on any java object are defined in object class. Object class is the parent class of any java class, whether it is predefined or programmer defined, hence all the object class methods are by default available to any java class. Object class define the following 11 methods

clone() : Creates a new object of the same class as this object.
equals(Object): Compares two Objects for equality.
finalize(): Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
getClass(): Returns the runtime class of an object.
hashCode(): Returns a hash code value for the object.
notify(): Wakes up a single thread that is waiting on this object's monitor.
notifyAll(): Wakes up all threads that are waiting on this object's monitor.
toString(): Returns a string representation of the object.
wait(): Waits to be notified by another thread of a change in this object.
wait(long): Waits to be notified by another thread of a change in this object.
wait(long, int): Waits to be notified by another thread of a change in this object.
toString(): To return String representation of an object.

public String toString()
{
return getClass.getName() + '@' + Integer.toHexString(HashCode);
}

Ex:

class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public static void main(String arg[])
{
Student s1 = new Student ("raju", 101);
Student s2 = new Student ("giri", 102);
System.out.println(s1); àStudent@10b62c9
System.out.println(s2); àStudent@82ba41
}
}

When ever we are passing object reference as argument to s.o.p() internally JVM will call toString() on that object. If we are not providing toString() then Object class toString() will be executed which is implemented as follows

public String toString()
{
Return getClass.getName() + ‘@’ + Integer.toHexString(hashCode);
}

Based on our requirement to provide our own String representation we have to override toString()

Ex:

If we are printing Student Object reference to return name & roll no we have to override
toString() as follows

public String toString()
{
return name+”--------“+rollno;
}

If we can place this toString() in student class then the O/P is
raju-----101
giri-----102
It is highly recommended to override toString() in our classes.

hashCode()

The hashCode of an Object just represents a random number which can be used by JVM while saving/adding Objects into Hashsets, Hashtables or Hashmap. hashCode() of Object class implemented to return hashCode based on address of an object, but based on our requirement we can override hashCode() to generate our own numbers as hashCodes

Case1:

class Test
{
int i;
Test(int i)
{
this.i = i;
}
public int hashCode()
{
return i;
}
public static void main(String arg[])
{
Test t1 = new Test(100);
Test t2 = new Test(110);
System.out.println(t1); 64
System.out.println(t2); 6e
}
}

Case2:

class hashCodeDemo
{
int i;
hashCodeDemo(int i)
{
this.i = i;
}
public int hashCode()
{
return i;
}
public String toString()
{
return i + "";
}
public static void main(String arg[])
{
hashCodeDemo h1 = new hashCodeDemo(100);
hashCodeDemo h2 = new hashCodeDemo(110);
System.out.println(h1); à 100
System.out.println(h2); à 110
}
}

equals()

Ex:
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public static void main(String arg[])
{
Student s1 = new Student ("raju", 101);
Student s2 = new Student ("giri", 102);
Student s3 = new Student ("giri", 102);
System.out.println(s1.equals(s2)); false
System.out.println(s2.equals(s3)); false
}
}

r1 == r2 à reference Comparision.
r1.equals(r2) à reference.

Note: In this case Object class .equals() has executed which is meant for reference comparison but based on our requirement it is recommended to override .equals() for content comparison. By over loading .equals() we have to consider the following 3 cases
Case1: The meaning of equality
Case2: In the case of heterogeneous objects we have to return false. (i.e) we have to handle
ClassCastException to return false.
Case3: If we are passing null as the argument we have return false. (i.e) we have to handle
NullPointerException to return false.

Overridden methods of equals
Ex:
class Student
{
String name;
int rollno;
Student(String name,int rollno)
{
this.name = name;
this.rollno = rollno;
}
public boolean equals(Object obj)
{
try
{
String name1 = this.name;
int rollno1 = this.rollno;
Student s2 = (Student)obj;
String name2 = s2.name;
int rollno2 = s2.rollno;
if(name1.equals(name2) && rollno1 == rollno2)
{
return true;
}
else
{
return false;
}
}
catch (ClassCastException c)
{
return false;
}
catch (NullPointerException e)
{
return false;
}
}
public static void main(String arg[])
{
Student s1 = new Student ("raju", 101);
Student s2 = new Student ("giri", 102);
Student s3 = new Student ("giri", 102);
System.out.println(s1.equals(s2)); false
System.out.println(s2.equals(s3)); true
System.out.println(s1.equals(null)); false
}
}
Comparison between ‘==’ operator and ‘.equals()’

==
.equals()
1) It is an operator and applicable for
both primitive and Object references.

1) It is a method applicable for Only
Object reference.

2) For Object reference r1, r2 r1 ==
r2 is true iff both r1 and r2 pointing
to the same object on the heap i.e it is
meant for reference comparision.

2) Default implementation available in
Object class is meant for reference
comparison only i.e r1.equals(r2) is true iff
both r1,r2 are pointing to the same object
on the heap.

3) We can’t override == operator.
3) We can override equals() for content
comparison.

4) IF r1 & r2 are incompatible then
r1 == r2 results Compile Time Error.

4) If r1 & r2 are incompatible then
r1.equals(r2) is always false.

5) For any Object reference r, r ==
null returns false.


5) For any Object reference r,
r.equals(null) returns false.

Relationship between ‘==’ and .equals()

If r1 == r2 is true then r1.equals(r2) is always true.
If r1.equals(r2) is true, then r1 == r2 need not to be true.

Contract Between .equals() and hashCode()

1)      If two objects are equal by .equals() then their hashcodes must be equal.

Ex:
If r1.equals(r2) is true then
r1.hashCode() == r2.hashCode is also true.
2) If two Objects are not equal by .equals() then their hashCode may or may not be same.
3) If the hashCodes of two Objects are equal then the objects may or may not be equal by .equals()
4) If the hashCodes of two Objects are not equal then the Objects are always not equal by .equals().

To satisfy above contract when ever we are overriding .equals it is highly recommended to override hashCode() also.

clone()

The process of creating exactly duplicate Object is called Clonning. Object class contains the clone method to perform this protected native Object clone() throws CloneNotSupportedException

Ex:

class Test implements Cloneable
{
int i = 10;
int j = 20;
public static void main(String arg[])throws CloneNotSupportedException
{
Test t1 = new Test();
Test t2 = (Test)t1.clone();
t1.i = 100;
t1.j = 200;
System.out.println(t2.i+"----"+t2.j); 10----20
}
}

All the Objects can’t have the capability to produce cloned Objects. Only clonaeble objects having that capability. An Object is said to be cloneable iff the corresponding class has to implement java.lang.cloneable interface. It doesn’t contain any methods it is a marker interface. Protected members can be accessible from outside package in the child classes but we should invoke them by using child class reference only. That is parent class reference is not allowed to invoke protected members from outside package.

class Test implements Cloneable
{
public static void main(String arg[])throws CloneNotSupportedException
{
Case1: Object o = new Object();
Object o2 = o.clone();
Case2: Object o = new Test();
Object o2 = o.clone();
Case3: Test t = new Test();
Object o = t.clone();
}
}

It is highly recommended to override clone() in our class like doGet(), doPost() methods.

Strings Class

Once we created String objects we are not allowed to perform any changes in the existing object. If u r trying to perform any changes with those changes a new String object will be created this behavior is nothing but ‘immutability’ Of the String Objects.

Ex:

String s1 = new String("raju");
s1.concat("Lesto");
System.out.println(s1);

O/P:- raju
Once we created a StringBuffer object we are allowed perform any changes in the existing object only. This behavior is nothing but ‘mutability’ of the StringBuffer object.

Ex:

StringBuffer sb1 = new StringBuffer("raju");
sb1.append("Lesto");
System.out.println(sb1);

O/P:- rajuLesto

Ex:

String s1 = new String("lesto");
String s2 = new String("lesto");
System.out.println(s1 == s2); à false
System.out.println(s1.equals(s2)); à true
In String class .equals method is overridden for content comparision.

StringBuffer sb1 = new StringBuffer("lesto");
StringBuffer sb2 = new StringBuffer("lesto");

System.out.println(sb1 == sb2) àfalse
System.out.println(sb1.equals(sb2));à false

In the StringBuffer .equals method is not overridden for content comparison. Hence Object class .equals method will be executed which is meant for reference comparison.

Difference Between (String s = new String(“raju”)) and (String s = “raju”)?
String s = new String(“raju”):-

In this case 2 objects will be created one is on the heap and the second one is on the scp(String constant pool) and ‘s’ is referring to heap object.

Object Creation in SCP is Optional.
If the object is not available then only a new object will be created.

String s = “raju”:-

In this case only one object will be created if it is not already available and ‘s’ is referring to that object. If an object is already available with this can in scp then ‘s’ will refer that existing object only instead of creating new object.

Note:- The Object present in the scp is not eligible for garbage collection even though the object doesn’t have any reference variables. All the scp objects will be destroyed at the time of JVM shutdown.

Ex:

String s1 = new String("maha");
String s2 = new String("maha");
String s3 = "maha";
String s4 = "maha";
Note:- In the scp there is no chance of 2 string objects with the same content i.e duplicate string objects won’t present in scp. But in the case of heap there may be a chance of duplicate stringObjects

Ex:

String s1 = new String("Sai");
1.concat("Kiran");
String s2 = "SaiKiran";
System.out.println(s1);
System.out.println(s2);
O/P:- Sai
SaiKiran

String s1 = "spring";
String s2 = s1+"summer";
s1.concat("fall");
s2.concat(s1);
s1=s1+"winter";
System.out.println(s1)

O/P:- springwinter
Springsummer

Ex:

class StringTest
{
public static void main(String[] args)
{
String s1 = new String("You cannot change me");
String s2 = new String("You cannot change me");
System.out.println(s1==s2);
String s3 = "You cannot change me";
System.out.println(s1==s3);
String s4 = "You cannot change me";
System.out.println(s3==s4);
String s5 = "You cannot"+" change me";
System.out.println(s4==s5);
String s6 = "You cannot";
String s7 = s6 + " change me";
System.out.println(s4==s7);
final String s8 = "You cannot";
String s9 = s8 + " change me";
System.out.println(s4==s9);
}
}

Importance of String Constant Pool(SCP)

In our program if any string object is repeatedly going to use, we can create only one object in the string constant pool and shared by several required references. Instead of creating several string objects with the same content creating only one object improves performance of the system and memory utilization also. This is biggest advantage of SCP. As the Several references pointing to the same object in SCP by using one reference if u r allowed to change the content the remaining references may be effected. Hence once we created a String object.
We r not allowed to change it’s content. If u r trying to change with those changes a new object will be created and there is no impact on the remaining references. This behavior is nothing but immutability of the string objects. SCP is the only reason why the String Objects are immutable.
Interning of String Objects

class StringTest
{
public static void main(String[] args)
{
String s1 = new String("raju");
String s2 = s1.intern();
String s3 = "raju";
System.out.println(s2 == s3);
}
}

At any point of time if we have heap object reference we can find it’s equivalent SCP Object by using intern() method. If the equivalent SCP Object is not already available then intern() method will create a new object in the SCP.

Ex:

class StringTest
{
public static void main(String[] args)
{
String s1 = new String("raju");
String s2 = s1.concat("lesto");
String s3 = s2.intern();
String s4 = “rajulesto”;
System.out.println(s3 == s4);
}
}

String Class Constructor

1) String s = new String();
Creates an empty String Object.
2) String s = new String(String literal);
3) String s = new String(StringBuffer s);
4) String s = new String(char [] ch);

char[] ch = {‘a’,’b’,’c’,’d’};
String s = new String(ch);
System.out.println(s);

O/P:--abcd

5) String s = new String(byte[] b);
byte[] b = {100,101,102,103,104};
String s = new String(b);
System.out.println(s);

O/P:--defgh.

Important Methods of String Class

1)      public char charAt(int index);

Ex:-

String s = “raju”;
System.out.println(s.chatAt(2)); O/P----j
System.out.println(s.charAt(10)); O/P----StringIndexOutOfBoundsException.

2) The overloaded ‘+’ and ‘+=’ operators acts as concatenation operation only.
Public String concat(String s)

Ex:- String s = ”raju”;
s = s.concat(“lesto”);
s = s+”lesto”;
s += “lesto”;
System.out.println(s);

3)(i) Public Boolean equals(Object o) It checks for content comparision. in this case of hetrogenious objects this method returns false.

String s = "lesto";
System.out.println(s.equals("LESTO"));
System.out.println(s.equals("lesto"));
(ii) Public Boolean equalsIgnoreCase(String s);
String s = "lesto";
System.out.println(s.equalsIgnoreCase("LESTO"));

Note:- Usually for validating username(where the case is not important method, we can use equals ignore case method) But for validating passwords we can use eauals method where the case is important.

4) public int length();

String s = "lesto";
System.out.println(s.length); O/P:-C.E
System.out.println(s.length()); O/P:-5
length is the variable applicable for array objects,But length() is the method applicable for String Object.

5) public String replace(char old, char new);

String s = "ababa";
System.out.println(s.replace('a','b'));

O/P:-bbbbb

6) (i)public String substring(int begin);

String s = "abcdefgh";
System.out.println(s.substring(3));

O/P:-defgh

(ii)public String substring(int begin, int end);
Returns the characters from (begin) index to (end-1) index.
String s = "abcdefgh";
System.out.println(s.substring(3,6));

O/P:-def.

7) public String toLowerCase();
public String toUpperCase();

Ex:-
 String s = “RoyalChallange”;
 System.out.println(s.toLowerCase());
 System.out.println(s.toUpperCase());

8) public String trim() to remove blank spaces present at Starting and Ending of the Sting. But not middle blank spaces.

String s = " raju 12 ";
System.out.println(s.trim());
O/P:-raju 12

9) public int indexOf(char ch);
returns first occurance index
public int lastIndexOf(char ch);

StringBuffer Class
Constructors of StringBuffer:
StringBuffer sb = new StringBuffer();
Creates an empty StringBuffer object with default initial capacity 16.
If it reaches max capacity then a new StringBuffer object will be created with new capacity is
Ex:-
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
sb.append("abcdefghijklmnop");
sb.append("q");
System.out.println(sb.capacity()); - 34
Ex:-

StringBuffer sb = new StringBuffer(40);
System.out.println(sb.capacity());
sb.append("abcdefghijklmnop");
.
.
.
.
Creates an empty StringBuffer with the required initial capacity.
StringBuffer sb = new StringBuffer(String s);
Creates an equivalent StringBuffer object for the given string with

Ex:-

StringBuffer sb = new StringBuffer(“Lesto”);
System.out.println(sb.capacity()); à 16 + 5 = 21

Important Methods of StringBuffer class

1)public int length();
2)public int capacity();
3)public char charAt(int index);

Ex:-

StringBuffer sb = new StringBuffer(“Lesto”);
System.out.println(sb.charAt(3));
System.out.println(sb.chatAt(10)); àStringIndexOutOfBoundsException.
capacity = (currentcapacity + 1) * 2
capacity = s.length() + 16

4)public void set chatAt(int index, char ch);
Replaces the character present at specified index with the provided char.

Ex:-

StringBuffer sb = new StringBuffer(“”);
sb.setCharAt(3,’a’);
System.out.println(sb);
5)public StringBuffer append(String s)
Allows all overloaded methods….int, float, byte, boolean, char[], byte[],….etc

6)public StringBuffer insert(int index, String s)

Ex:-

StringBuffer sb = new StringBuffer(“Lesto”);
sb.insert(2,”raju”);
System.out.println(sb); StringBuffer sb = new StringBuffer(String s);

7) public StringBuffer delete(int start, int end)

delete characters from start to (end-1)
StringBuffer sb = new StringBuffer(“abcdefgh”)
sb.delete(2,6);
O/P:-abgh

8) public StringBuffer delete charAt(int index)
deleting Character located at specified index.

9) public StringBuffer reverse();

Ex:-

StringBuffer sb = new StringBuffer(“raju”);
Syetem.out.println(sb.reverse());
 O/P:-ujar.

10) public void setLength(int requiredlength);

Ex:- StringBuffer sb = new StringBuffer(“ aishwaryaabhishak”);
sb.setLength(8);
System.out.println(sb)
O/P:-aishwarya

Note:-All the methods which are available in the StringBuffer are Sunchronized or it may effect the performance of the system. We can overcome this problem by using StringBuilder.

StringBuilder

StringBuilder class exactly similar to StringBuffer (including constructors and methods) Except the following.


StringBuilder
StringBuffer

No method is synchronized
All methods are Synchronized

StringBuilder is not thread safe
StringBuffer is thread safe

Performance is high
Performance is very low
Available only in 1.5 version
Available from 1.0 version


If the content is not changing frequently then we should go for the string.
If the content will change frequently and thread safety is required then we should go for StringBuffer. If the content is changing frequently and thread safety is not required then we should go for StringBuilder.

Chaining of Methods

For most of the methods in String and StringBuffer the returntypes are the same String and StringBuffer objects only. After Applying a method we are allowed to call another method on the result which forms a method change. sb.m1().m2().m3().m4().m5()…..;

All these method calls will execute from left to right.

StringBuffer sb = new StringBuffer(“raju”);
sb.append("software").reverse().insert(2,"abc").delete(2,5).append("xyz");

Wrapper Classes

The main objectives of wrapper classes are:
1) To Wrap primitives into object form. So that we can handle primitives also just like objects.
2) To Define several utility functions for the primitives(like converting primitive to the string form etc.)

Constructors:

valueOf()
xxxValue()
parseXxx()
toString()

Constructing Wrapper objects by using constructors

Every Wrapper class contains 2 constructors one can take the corresponding primitive as the
argument and the other can take the corresponding string as the argument.

Ex:
Integer I = new Integer(10);
Integer I = new Integer(“10”);

If the String is unable to convert into the number form then we will get runtime exception saying “NumberformatException”.

Ex: Integer I = new Integer(“ten”);
Float class contains 2 constructors which can take double String as argument.
Float f = new Float(10.5f);
Float f = new Float(“10.5f”);
Float f = new Float(10.5);
Float f = new Float(10.5);

Character class contain only one constructor which can take char as the argument i.e character class doesn’t contain a constructor which can take string as the argument.

Ex:

Character ch1 = new Character('a'); à valid.
Character ch1 = new Character("a"); à not valid.
Boolean class contains 2 constructors one can take boolean primitive. Other can take string
argument. If u r providing boolean primitive as the argument the. The allowed values are true or false. Case is not important if the content contains ‘TRUE’ then it is considered as true other wise it considered as false.

Q) Which of the following are valid ?

Boolean b = new Boolean(true); O/P:-true
Boolean b = new Boolean(FALSE); X
Boolean b = new Boolean(“false”); O/P:-false
Boolean b = new Boolean(“TrUE”); O/P:-true
Boolean b = new Boolean(“raju”); O/P:-false
Boolean b = new Boolean(“yes”); O/P:-false

Q) Consider The Following:

Boolean b1 = new Boolean(“yes”);
Boolean b2 = new Boolean(“No”);
System.out.println(b1.equals(b2));
1) C.E
2) R.E
3) true
4) false
Ans: 3 (true)

valueOf( ) methods

version1:
All the wrapper classes except character class contains the valueOf() method for converting
string to corresponding Wrapper Object. public static wrapper valueOf(String s);

Ex:

Integer I = Integer.valueOf(‘10’);
Float F = Float.valueOf(“10.5”);
Boolean B = Boolean.valueOf(“raju”);
Character ch = Character.valueOf(“10”); Xà C.E


Version2:
All Integral wrapper classes “Byte, Short, Long, Integer” Contains the following valueOf()
method. public static wrapper valueOf(String s, int radix); The allowed base of radix is 1 to 36.Because Numerics(10) ,Alphabets(26) finally 10+26 =36

Ex:

Integer I = Integer.valueOf(“101011”, 2);
System.out.println(I); O/P:- 43

Version3:

Every Wrapper class including character class contains the following valueOf() method to
convert primitive to wrapper object form.
public static wrapper valueOf(primitive p);

Ex:

Integer I = Integer.valueOf(10);
Character ch = Character.valueOf(‘a’);
Boolean B = Boolean.valueOf(true);
Version1, Version2 String to wrapper object.
Version3 primitive to wrapper object.
WrapperClasses constructor arguments
Byte byte (or) string
Short short (or) string
Integer int (or) string
Long long (or) string
Float float (or) string (or) double
Double double (or) string
Character char
Boolean boolean (or) string

xxxValue() method

Every wrapper class Except character and Boolean classes contains the following xxxValue() methds  for converting wrapperObject to primitive.

public int intValue();
public byte byteValue();
public short shortValue();
public long longValue();
public float floatValue();
public int doubleValue();

Ex:

Integer I = Integer.valueOf(130);
System.out.println(I.byteValue());
System.out.println(I.shortValue()); à-126
System.out.println(I.intValue()); à130
System.out.println(I.langValue()); à130
System.out.println(I.floatValue()); à130.0
System.out.println(I.doubleValue()); à130.0

Character class contain charValue() method to return char primitive for the given character
wrapper object. public char charValue();

Ex:

character ch = new character(‘a’);
char ch = ch.charValue();
System.out.println(ch1); O/P:- a

Boolean class contains booleanValue() method to return boolean primitive for the given boolean objective.

Boolean B = Boolean.valueOf("Tea Break");
boolean b1 = B.booleanValue();
System.out.println(b1); O/P:-false

Note:- In total 38 xxxValue methods are possible ((6 X 6) +1 + 1) = 38

parseXxx() methods

version1:

Every wrapper class except character class contains the following parseXxx() method for
converting String to primitive type public static primitive parseXxx(String s);

Ex:

int i= Integer.valueOf(“10”);
Boolean b = Boolean.parseBoolean(“true”);

Version2:

Integral wrapper classes(Byte, Short, Integer and long ) contains the following parseXxx()
method.

public static primitive parseXxx(String s, int radix );
int i = Integer.parseInt(“101011”, 2);
System.out.println(i); O/P:-43



toSting()methods

version1:

All wrapper Classes contains an instance method toString() for converting wrapper object to
String type. This is overriding method of object class toString() method.

public String toString();

Integer I = new Integer(10);
String s = I.toString();
System.out.println(s); O/P:-10

Boolean B = new Boolean(“raju”);
String s = B.toString();
System.out.println(s); O/P:-false

Version2:

Every wrapper class contains the following static toString() for converting primitive to String
representation..

public static String toString(primitive p);

String s = Integer.toString(10);
System.out.println(s); O/P:-10

String s = Boolean.toString(true);
System.out.println(s); O/P:-true

Version3:

Integer and long classes contains the following toString() to return the String in the specified
radix.

public static String toString(int/long, int radix );

String s = Integer.toString(43, 2);
System.out.println(s); O/P:-“101011”

String s = Integer.toString(43, 8);
System.out.println(s); O/P:-“53”

Version4:

Integer and Long classes contains the following methods to return specified radix String
form.

public static String toBinaryString(int/long, l);
public static String toOctalString(int/long, l);
public static String toHexString(int/long, l);

String s = Integer.toBinaryString(43);
System.out.println(s); O/P:-“101011”

String s = Integer.toOctalString(43);
System.out.println(s); O/P:-“53”

String s = Integer.toHexString(43);
System.out.println(s); O/P:-“262”

Partial Hirarchy of java.lang Package

Void is also considered as wrapper class. String, StingBuffer, StringBuilder and all wrapper class are final. In Addition to String Object all wrapper class objects also immutable. Boolean and Character wrapper classes are not child classes or Number class

Objecct
-------
String StringBuffer StringBuilder Math Void
Number
Boolean Character
Byte Short
Integer Long Float

No comments: