0% found this document useful (0 votes)
162 views14 pages

06 Java - Lang Package

The document discusses key classes in the java.lang package, including Object, String, StringBuffer, and wrapper classes. It provides details on common methods like toString(), hashCode(), and equals() in the Object class. The toString() method returns a string representation of an object, hashCode() returns a unique number, and equals() checks equivalence between objects. Overriding these methods allows customizing their behavior.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
162 views14 pages

06 Java - Lang Package

The document discusses key classes in the java.lang package, including Object, String, StringBuffer, and wrapper classes. It provides details on common methods like toString(), hashCode(), and equals() in the Object class. The toString() method returns a string representation of an object, hashCode() returns a unique number, and equals() checks equivalence between objects. Overriding these methods allows customizing their behavior.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 14

java.lang.

package
 For writing any java program the most commonly required classes and interfaces are
encapsulated in the separate package which is nothing but java.lang package.
 It is not required to import java.lang package in our program because it is available by
default to every java program.

The following are some of important classes present in java.lang package.

1. Object class
2. String class
3. StringBuffer class
4. StringBuilder class (1.5 v)
5. Wrapper Classes
6. Autoboxing and Autounboxing(1.5 v)

1) Java.lang.Object class:

1. For any java object whether it is predefine or customized the


most commonly required methods are encapsulated into a
separate class which is nothing but object class.
2. As object class acts as a root (or) parent (or) super for all java
classes, by default its methods are available to every java
class.

Note: If our class doesn't extends any other class


then it is the direct child class of object
if our class extends any other class then it is the
indirect child class of Object.

In right side image class A indirectly extends to class


object from B class

The following is the list of all methods present in java.lang Object class :

1. public String toString();


2. public native int hashCode();
3. public boolean equals(Object o);
4. protected native Object clone()throws CloneNotSupportedException;
5. public final Class getClass();
6. protected void finalize()throws Throwable;
7. public final void wait() throws InterruptedException;
8. public final native void wait()throws InterruptedException;
9. public final void wait(long ms,int ns)throws InterruptedException;
10. public final native void notify();
11. public final native void notifyAll();
1) toString() Method:

We can use this method to get string representation of an object

If you print any object, java compiler internally invokes the toString() method on the object. So
overriding the toString() method(which is present in Object class), returns the desired output,
it can be the state of an object etc. depends on your implementation.

Inbuilt toString() Method present in Object class

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.

Problem without toString() method

 In the above program Object class toString() method got executed.


 As you can see in the above example, printing s1 and s2 prints the hashcode values
of the objects but I want to print the values of these objects. Since java compiler
internally calls toString() method, overriding this method will return the specified
values. Let's understand it with the example given below:
E.g. using (overriding) toString() method

To provide our own String representation we have to override toString() method in our class.

Note: In String class, StringBuffer, StringBuilder, wrapper classes and in all collection classes
toString() method is overridden for meaningful string representation. Hence in our classes
also highly recommended to override toString() method.
2)hashCode() method :

 For every object jvm will generate a unique number which is nothing but hashCode.
 Jvm will using hashCode while saving objects into hashing related data structures like
HashSet, HashMap, and Hashtable etc.
 If the objects are stored according to hashCode searching will become very efficient
(The most powerful search algorithm is hashing which will work based on hashCode).
With following search strategies you’ll come to know why hashing is powerful in searching:-
Linear search:-
1) A linear search scans one item at a time, without jumping to any item.
2) Time taken to search elements keep increasing as the number of elements are
increased.

Binary search
1) A binary search however, cut down your search to half as soon as you find middle of
a sorted list.
2) The middle element is looked to check if it is greater than or less than the value to be
searched.
3) Accordingly, search is done to either half of the given list

Hashing:
1) Save items in a key-indexed table (index is a function of the
key).
2) Hash function.
Method for computing table index from key

Here we can find particular element from hash codes which sorted
already, so it is much easy to search element. Hence time required
for searching is almost nothing.
toString() method vs hashCode() method Relationship
in implemention toString() method of Object class hashCode() method is present
shown as below.

In this case Object class toString( ) method got executed


which is internally calls Test class hashCode( ) method. In this case Object class toString() method got
executed which is internally calls Object class
hashCode( ) method.

In below case Test class toString() method got executed. Which don’t includes hashMap() method.
What is Typecasting in Java?

In inheritance if super class’s reference variable wants to access non overridden


methods of subclass then typecasting is needed.

Syntax: ((subclass_name).object of Superclass)

In above e.g. Class A can’t access printFromB() method of subclass then typecasting
is needed.

3) equals() method (See first in next page mentioned Diff b/t == & .equal() for reference)

1. We can use this method to check equivalence of two objects.


2. If our class doesn't contain .equals() method then object class .equals() method will be
executed which is always meant for reference comparison. i.e., if two references
pointing to the same object then only .equals( ) method returns true .

In the above program Object class .equals() method got executed which is always meant for reference comparison that is if
two references pointing to the same object then only .equals(() method returns true.

In object class .equals() method is implemented as follows which is meant for reference comparison.
Based on our programming requirement we can override .equals() method for
content comparison purpose.
Whenever we are overriding .equals() method we have to consider the following things
because we have to exactly override this method, how it is declared in object class i.e.
If we are passing different type of objects (heterogeneous object) our .equals() method
should return false as object class’s method does for its .equals(method):

1) Meaning of content comparison i.e., whether we have to check the names are equal
(or) roll numbers (or) both are equal (i.e. based on our assumption what will be the
criteria for equality for e.g. person object should be declare equal on the bases of only
name (or) name, Age (name, age, address….)).
2) If we are passing different type of objects (heterogeneous object) our .equals() method
should return false but not ClassCastException i.e., we have to handle
ClassCastException to return false.
3) If we are passing null argument our .equals() method should return false but not
NullPointerException i.e., we have to handle NullPointerException to return false.
4) The following is the proper way (as overridden in Object class)of overriding .equals()
method for content comparison in Student class.
More simplified version of overridden .equals() method as follows

To make .equals() method more efficient we have to place the following code at the top inside .equals() method.

If 2 references pointing to the same object then .equals() method return true directly without performing any content
comparison this approach improves performance of the system

Previously written method can be written in simpler form as above

Note: In String class, Wrapper classes and all collection classes .equals( ) method is
overridden for content comparison.
Differences between == (double equal operator) and .equals() method

== (double equal operator) .equals() method


It is an operator applicable for both primitives and object It is a method applicable only for object references but not for
references. primitives.
In the case of primitives == (double equal operator) meant for
By default .equals() method present in object class is also meant
content comparison, but in the case of object references == operator
for reference comparison.
meant for reference comparison.
We can't override== operator for content comparison in object
We can override .equals() method for content comparison.
references.

If there is no relationship between argument types then .equals()


If there is no relationship between argument types then we will get method simply returns false and we won't get any compile time
compile time error saying incompatible types.(relation means child error and runtime error.
to parent or parent to child or same type) Because it’s already defind in .equal() method
if(obj instanceof Student) else return fasle like in above programe

For any object reference r, r==null is always false. For any object reference r, r.equals(null) is also returns false.

Note: in general (not officialy) we can use == (double equal operator) for reference
comparison whereas .equals() method for content comparison by overriding it.

Relationship between .equals() method and ==(double equal operator)

1. If r1==r2 is true then r1.equals(r2) is always true i.e., if two objects are equal by == operator
then these objects are always equal by .equals( ) method also.
2. If r1==r2 is false then we can't conclude anything about r1.equals(r2) it may return true (or)
false (In case in .equals() method overridden for content comparison).

I.e. Student s1=new Student("Sagar",101); & Student s3=new Student("Sagar",101);

3. If r1.equals(r2) is true then we can't conclude anything about r1==r2 it may returns true (or)
false.(vice versa case of above)
4. If r1.equals(r2) is false (i.e neither content nor reference is true) then r1==r2 is always false.

Contract between .equals() method and hashCode() method:


Note: Hashing related Data structures follows the following fundamental rules.
Two equivalent object should be placed in same bucket but all objects present in the
same bucket need not be equal.

1. If 2 objects are equal by .equals() method compulsory their hashcodes must be same.
That is If r1.equals(r2) is true then r1.hascode()==r2.hashcode( ) must be true.
2. If 2 objects are not equal by .equals() method then there are no restrictions on
hashCode() methods. They may be same (or) may be different. That is If r1.equals(r2)
is false then r1.hashCode()==r2.hashCode() may be same (or) may be different.
3. If hashcodes of 2 objects are equal we can't conclude anything about .equals() method
(as it may content based or reference based comparison) it may returns true (or) false.
That is If r1.hashCode()==r2.hashCode() is true then r1.equals(r2) method may
returns true (or) false.
4. If hashcodes of 2 objects are not equal then these objects are always not equal by
.equals() method also. That is If r1.hashCode()==r2.hashCode() is false then
r1.equals(r2) is always false.

To maintain the above contract between .equals() and hashCode() methods whenever we are
overriding .equals() method. compulsory we should override hashCode() method by
implementing above 4 contracts. Violation leads to no compile time error and runtime error but
it is not good programming practice.

Same hashcode

In String class .equals() method is overridden for content comparison & hence hashcode() method is also overridden to
generate hashcode based on content.

Different
hashcode

In StringBuffer class .equals() method is not overridden for content comparison & hence hashcode() method is also not
overridden.
Which of the following is appropriate way of overriding hashCode() method?

Here String class’s hashcode method gets called.

Based on whatever the parameters we override ".equals()


method" we should use same parameters while overriding
hashCode() method also.

Note: in all wrapper classes, in string class, in all collection


classes .equals() method is overridden for content comparison
in our classes also it is highly recommended to override .equals()
method.
4) Clone () method:

1. The process of creating exactly duplicate object is called cloning.


2. The main objective of cloning is to maintain backup purposes. (i.e., if something goes
wrong we can recover the situation by using backup copy.)
3. We can perform cloning by using clone() method of Object class.(Syntax given below)

protected native object clone() throws CloneNotSupportedException;

The java.lang.Cloneable interface must be


implemented by the class whose object clone we
want to create.
If we don't implement Cloneable interface, clone()
method generates CloneNotSupportedException.

1) Shallow cloning:
1) The process of creating bitwise copy of an object is called Shallow
Cloning.
2) If the main object contain any primitive variables then exactly
duplicate copies will be created in cloned object.
3) If the main object contain any reference variable then the
corresponding object won't be created just reference variable will
be created by pointing to old contained object.
4) By using main object reference if we perform any change to the
contained object then those changes will be reflected automatically
to the cloned object.
5) by default Object class clone( ) meant for Shallow Cloning
6) Shallow cloning is the best choice, if the Object contains only primitive values.
7) To overcome this problem we should go for Deep cloning.

2) Deep Cloning:
1) The process of creating exactly independent duplicate object (including contained
objects also) is called deep cloning.
2) In Deep cloning, if main object contain any reference variable then the corresponding
Object copy will also be created in cloned object.
3) Object class clone( ) method meant for Shallow Cloning , if we want Deep cloning
then the programmer is responsible to implement by overriding clone( ) method.

4) In Deep cloning by using main Object reference if we perform any change to the
contained Object those changes won't be reflected to the cloned object.

You might also like