Java - Lang Package by Durga Sir
Java - Lang Package by Durga Sir
lang package
1. Introduction
2. Object class
3. String class
4. StringBuffer class
5. StringBuilder class
6. wrapper class
7. Autoboxing and Autounboxing
Introduction:
1. For writing any java program whether it is simple or complex, the
most commonly require classes and interfaces are grouped into a
separate package which is nothing but java.lang package.
2. We are not required to import java.lang package explicitly
because all classes and interfaces present in lang package by
default available to every java program.
Java.lang.Object:
1. The most commonly required methods for every java class (whether it
pre-define class or customized class) are define in a separate class
which is nothing but Object class.
2. Every class is the child class of object either directly or indirectly.
So that, object class methods by default available to every java class.
Hence Object class is considered as root of all java classes.
Note:
If our class doesn’t extends any other class then only our class is the
direct child class of Object class.
package langpack;
public class A {
A--------> Object
If our class extends any other class then our class is indirect child
class of Object class.
package langpack;
public class A {
}
package langpack;
}
A---------->B--------->Object----multi-level inheritance
Note:
Strictly speaking object class contains 12 methods. The extra method
registerNatives().
This method is internally required for object class and not available
to the child classes. Hence we are not required to consider this
method.
toString() method:
1. we can use toString() method to get String representation of an object.
Sting s = Obj.toString();
Syso(s);
2. whenever we are trying object reference internally toString() method
will be called.
Example;
Syso(s)-----> syso(s.toString());
package langpack;
System.out.println(s);
System.out.println(s.toString());
System.out.println(s1);
}
}
Output:
langpack.Student@15db9742
langpack.Student@15db9742
langpack.Student@6d06d69c
In the above example Object class toString() method got executed which is
implemented as follows:
className@hashCode_in_hexaDecimal_form
Example:
Whenever we are trying to print student object reference to print his name
and roll no. we have to override toString() method as follows:
package langpack;
System.out.println(s);
System.out.println(s.toString());
System.out.println(s1);
}
}
Output:
lalit 100
lalit 100
durga 101
package langpack;
import java.util.ArrayList;
}
Output:
Lalit
10
[A, B]
test
hashCode() method:
1. For every object a unique number is generated by JVM which is nothing
but hashCode.
2. hashCode won’t represent address of object.
3. JVM will use hashCode while saving objects into hashing related data
structures like hashTable,hashMap,HashSet etc.
4. The main advantage of saving objects based on hashCode is searching
operation will become easy (the most powerful search algorithm up to
today is hashing.)
5. If you are giving the chance to object class hashCode() method, it will
generate hash code based on address of the object. It doesn’t mean hash
code represents address of the object.
6. Based on our requirement we can override hashCode() method in our class
to generate our own hash code.
7. Overriding hashCode() method is said to be proper if and only if for
every object we have to generate a unique number as hash code.
package langpack;
This is improper way of overriding hashCode() method because for all student
objects we are generating same number as hash code.
package langpack;
int rollNo;
toString() VS hashCode():
1. If we are giving are object class toString() method, it will
intwrnally calls hashCode() method.
2. If we are overriding toString() method then our toString() method
may not call hashCode() method.
package langpack;
int rollNo;
System.out.println(t1);
System.out.println(t2);
}
}
Output:
langpack.Test@15db9742
langpack.Test@6d06d69c
package langpack;
int rollNo;
@Override
public int hashCode() {
// TODO Auto-generated method stub
return rollNo;
}
public static void main(String[] args) {
Test t1 = new Test(101);
Test t2 = new Test(102);
System.out.println(t1);
System.out.println(t2);
}
}
Output:
langpack.Test@65
langpack.Test@66
package langpack;
@Override
public String toString() {
return rollNo + "";
// TODO Auto-generated method stub
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return rollNo;
}
public static void main(String[] args) {
Test t1 = new Test(101);
Test t2 = new Test(102);
System.out.println(t1);
System.out.println(t2);
}
}
Output:
101
102
Equals() method:
1. We can equals() method to check equality of two objects.
Obj1.equals(obj2)
2. If our class doesn’t contain equals() method then object class equals()
method will be executed.
package langpack;
String name;
int rollNo;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}
Output:
false
false
true
In the above example object class equals() method got executed which is meant
for reference comparison (address comparison) i.e if two references pointing
to the same object then only that equals() method returns true.
String name;
int rollNo;
Student s = (Student)obj;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}
}
Output:
false
true
true
package langpack;
String name;
int rollNo;
Student s = (Student)obj;
}
public static void main(String[] args) {
Student s1 = new Student("Lalit",101);
Student s2 = new Student("Bizlain",102);
Student s3 = new Student("Lalit", 101);
Student s4 = s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("lalit"));
System.out.println(s1.equals(null));
}
}
Output:
false
true
true
false
false
package langpack;
String name;
int rollNo;
}
public static void main(String[] args) {
Student s1 = new Student("Lalit",101);
Student s2 = new Student("Bizlain",102);
Student s3 = new Student("Lalit", 101);
Student s4 = s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("lalit"));
System.out.println(s1.equals(null));
}
}
Output:
false
true
true
false
false
package langpack;
public class Student{
String name;
int rollNo;
}
public static void main(String[] args) {
Student s1 = new Student("Lalit",101);
Student s2 = new Student("Bizlain",102);
Student s3 = new Student("Lalit", 101);
Student s4 = s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("lalit"));
System.out.println(s1.equals(null));
}
}
Output:
false
true
true
false
false
note:
To make above equals() method more efficient we have to write the following
code: at the beginning inside equals method.
package langpack;
String name;
int rollNo;
}
public static void main(String[] args) {
Student s1 = new Student("Lalit",101);
Student s2 = new Student("Bizlain",102);
Student s3 = new Student("Lalit", 101);
Student s4 = s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("lalit"));
System.out.println(s1.equals(null));
}
}
Output:
false
true
true
false
false
package langpack;
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
true
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
false
getClass() method:
2. By using this ‘Class’ class object we can access class level properties
like fully qualified name of the class, methods information,
constructors information etc.
package langpack;
import java.lang.reflect.Method;
Method[] m = c.getDeclaredMethods();
System.out.println("methods information");
for(Method m1 : m) {
count++;
System.out.println(m1.getName());
}
System.out.println("The number of methods :" + count);
}
}
Example2:
Syso(con.getClass.getName());
Note:
After loading every .class file JVM will create an object of the type
java.lang.class in the heap area. Programmer can use this class object
to get Class level information.
We can use getClass() method very frequently in reflections API.
Finalize() method:
package langpack;
}
Output:
Lalit
package langpack;
LalitBizlain
Output:
false
false
package langpack;
Output:
false
true
In String class .equals() method is overridden for content comparison.
Hence even though objects are different if content is same .equals()
method returns true.
Case3:
package langpack;
}}
In this case two objects will be created one in the heap area and the
other is in String constant pool (SCP) and s is always pointing to
heap object.
Heap SCP
package langpack;
}}
In this only one object will be created in SCP and s is always pointing to
that object.
Heap SCP
S Lalit
Note1:
Object creation in SCP is optional, 1st it will check is there any
object already present in SCP with the required content.
If object already present then existing object will be reused.
If object not already available then only a new object will be created.
But this rule is applicable only for SCP but not for the heap.
Note2:
Garbage collector is not allowed to access SCP area. Hence even
though object doesn’t contain reference variable, it is not
available for Garbage collector if it is present in SCP area.
All SCP objects will be destroyed automatically at the time JVM
shut down.
package langpack;
}}
Heap SCP
S1 Lalit Lalit
S2 Lalit S3 s4
Note:
System.out.println(s1);
System.out.println(s2);
}}
Output:
Lalitsoft
LalitLallit
heap SCP
S1 Lalit Lalit
LalitBizlain Bizlain
S2 LalitLallit Lallit
Lalitsoft soft
For every string constant one object will be placed in SCP area.
Create a string object and the heap for the give string literal.
package langpack;
Output:
abcd
package langpack;
Output:
efgh
package langpack;
Output:
i
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 20
at java.lang.String.charAt(String.java:658)
at langpack.Test.main(Test.java:9)
package langpack;
System.out.println(s );
}}
Output:
Lalit Bizlain Kumar Biz
package langpack;
System.out.println(s.equals("lalit"));
System.out.println(s.equalsIgnoreCase("lalit"));
}}
Output:
false
true
Note:
package langpack;
Output:
itBizlain
itBiz
package langpack;
System.out.println(s.length);
System.out.println(s.length());
12
}}
Length variable applicable for arrays but not for string objects.
Whereas length() method applicable for string objects but not for
arrays.
package langpack;
System.out.println(s.replace('a', 'b'));
}}
Output:
bbbbbb
To remove the blank spaces present at beginning and end of the string
but not middle blank spaces.
package langpack;
System.out.println(s.trim());
}}
Output:
ababab
package langpack;
System.out.println(s.indexOf('b'));
System.out.println(s.lastIndexOf('a'));
}}
Output:
2
5
package langpack;
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}}
Output:
false
true
false
true
Note:
Because of run time operation if there is any change in the content
then with those changes a new object will be created in the heap.
If there is no change in the content existing object will be reused
and new object won’t be created.
heap SCP
S1
durga durga
S3
S2 DURGA
package langpack;
}}
heap SCP
S1
durga durga
S3
S2 DURGA
S4 durga
S5 DURGA
package langpack;
public class Test{
}}
heap SCP
S1
durga
S2
S3
S4 DURGA
S5 durga
package langpack;
public Test(int i) {
this.i = i;
}
System.out.println(t1==t2);
System.out.println(t1==t3);
}
}
Output:
false
true
Once we create a Test object we can’t perform any change in the existing
object. If we are trying to perform any change and if there is a change in
the content then with those changes a new object will be created and if there
is no change in the content then existing object will be reused.
Final VS immutability:
1. Final applicable for variables but not for objects whereas
immutability applicable for objects but not for variables.
2. By declaring a reference variable as final we won’t get any
immutability nature. Even though reference variable is final, we
can perform any type of change in the corresponding object but we
can’t perform re-assignment for that variable.
3. Hence final and immutable both are different concepts.
package langpack;
sb = new StringBuffer("lalit");-----error
}
}
Output:
Lalit Bizlain
Java.lang.StringBuffer:
1. If the content is fixed and won’t change frequently then it is
recommended to go for String.
2. If the content is not fixed and keep on changing then it is not
recommended to use string because for every change a new object
will be created which effects performance of the system.
3. To handle this requirement we should go for StringBuffer.
4. The main advantage of stringbuffer over string is all required
changes will be performed in the existing object only.
Constructors of StringBuffer:
1. StringBuffer sb = new StringBuffer();
Create an empty StringBuffer object with default initial capacity 16. Once
StringBuffer reaches its max capacity, a new StringBuffer object will be
created with new capacity = (current capacity) + 1 * 2
package langpack;
}
}
Output:
16
16
34
34
70
Capacity = s.legth() + 16
package langpack;
}
}
Output:
29
29
60
60
60
package langpack;
Output:
13
29
i
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 30 at
java.lang.StringBuffer.charAt(StringBuffer.java:202) at
langpack.Test.main(Test.java:11)
package langpack;
Output:
Lalit bizlain
package langpack;
System.out.println(sb);
}
}
Output:
lalit Pie value is: 3.14, It is: true
package langpack;
public class Test{
System.out.println(sb);
}
}
Output:
lalit123 bizlain
package langpack;
System.out.println(sb);
}
}
Output:
nialzib tilal
package langpack;
public class Test{
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("lalit bizlain ");
sb.setLength(8);
System.out.println(sb);
}
}
Output:
lalit bi
package langpack;
Output:
16
1000
package langpack;
Output:
16
1000
5
StringBuilder:
StringBuffer StringBuilder
Note:
Except above differences everything is same in StringBuffer and
StringBuilder (including methods and constructors).
Method chaining:
1. For most of the methods in String, StringBuffer and
StringBuilder return types are same type. Hence after
applying a method and result we can call another method
which forms method chaining.
2. In method chaining all method calls will be execute always
from left to right.
Sb.m1().m2().m3().m4()………………
package langpack;
System.out.println(sb);
}
}
Output:
sziB til321aL
Wrapper classes:
1. The main objective of wrapper classes are:
To wrapped primitive into Object form so that we can
handle primitive also just like objects.
To define several utility methods which are required for
the primitives.
Example1:
Example2:
Float class contains three constructors one can take float, double as
primitive argument and other can take string argument.
Example4:
Character class contains only one constructor which can take char argument.
Example5:
If we are passing string type as argument then case and content both
are not important.
package langpack;
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
System.out.println(b5);
System.out.println(b6);
System.out.println(b7);
System.out.println(b8);
System.out.println(b9);
System.out.println(b10);
System.out.println(b11);
System.out.println(b12);
System.out.println(b1.equals(b2));
}
}
Output:
false
false
true
true
true
false
false
false
true
false
false
false
true
Note:
1. valueOf() methods:
We can use valueOf() methods to create wrapper object for the given
primitive or string.
a) Form1:
Every wrapper class except character class contains a
static value of method to create wrapper object for the
given string.
package langpack;
System.out.println(I);
System.out.println(d);
System.out.println(b);
}
}
Output:
10
10.5
False
b) Form2:
Every integral type wrapper class (Byte, Short, Integer, Long) contains the
following valueOf() method to create wrapper object for the given specified
radix string.
package langpack;
Output:
4
256
1296
c) Form3:
Every wrapper class including character class contains a
static valueOf() method to create wrapper object for the
given primitive.
package langpack;
Output:
10
a
true
2. xxxValue() method:
}
}
Output:
-126
130
130
130
130.0
130.0
package langpack;
}
}
Output:
a
Boolean class contains booleanValue() method to get boolean
primitive for the given Boolean object.
package langpack;
}
}
Output:
false
3. parseXXX() method:
we can use parseXXX() methods to covert string to primitive.
a) Form1:
Every wrapper class except character class contains the following
parseXXX() method to find primitive for the given String object.
package langpack;
System.out.println(i);
System.out.println(d);
System.out.println(b);
}
}
Output:
10
10.5
true
b) Forme2:
Every integral type wrapper class (Byte, Short, Integer, Long)
contains the following parseXXX() method to convert specified radix
string to primitive.
package langpack;
System.out.println(i);
}
}
Output:
625
4. toString() method:
we can use toString() method to convert wrapper object or primitive to
String.
1. Form1:
}
}
Output:
10
10
2. Form2:
package langpack;
String s1 = Integer.toString(10);
String s2 = Double.toString(10.5);
String s3 = Boolean.toString(true);
String s4 = Character.toString('a');
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
Output:
10
10.5
true
a
3. Form3:
Integer and Long classes contains the following toString() method to convert
primitive to specified radix string.
package langpack;
}
}
Output:
1111
package langpack;
public class Test{
String s1 = Integer.toBinaryString(15);
String s2 = Integer.toOctalString(15);
String s3 = Integer.toHexString(15);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output:
1111
17
f
String
toSting()
valueOf()
The wrapper classes which are not child class of Number are Boolean and
character.
The wrapper classes which are direct child class of Object are Byte,
Short, Integer, Long, Float, Double.
String, StringBuffer, StringBuilder and all wrapper classes are final
classes.
In addition string to objects all wrapper class objects also immutable.
Sometimes void class is also considered as wrapper class.
Void class:
If(getMethod(m1).getReturnType()==Void.Type)
Autoboxing:
1. Automatic conversion primitive to wrapper object by compiler is called
autoboxing.
Autounboxing:
1. Automatic conversion wrapper object to primitive by compiler is called
autounboxing.
Autoboxing[valueOf()]
Autounboxing[xxxValue()]
package langpack;
public class Test{
}
}
Output:
10
package langpack;
static Integer I = 0;
}
}
Output:
0
package langpack;
public class Test{
}
}
Output:
package langpack;
x++;
System.out.println(x);
System.out.println(y);
System.out.println(x==y);
}
}
Output:
11
10
false
All wrapper class objects are immutable i.e once we create wrapper
class object we can’t perform any changes that object. If we are
trying to perform any changes with those changes a new object will be
created.
10
x
10
y
11
package langpack;
System.out.println(x==y);
System.out.println(x1==y1);
System.out.println(x2==y2);
System.out.println(x3==y3);
System.out.println(x4==y4);
}
}
Output:
false
false
true
true
false
conclusion:
1. Internally to provide support for autoboxing a buffer of wrapper
objects will be created at the time of wrapper class loading.
2. By autoboxing if an object is required to create, 1 st JVM will check
whether this object already present in buufer or not.
3. If it is already present in buffer then existing buffer object will be
used.
4. If it is not already available in the buffer then JVM will create a new
object.
Class integer{
Static{
X y x1 y1
}
}
Except this range in all remaining cases a new object will be created.
package langpack;
System.out.println(x1==y1);
System.out.println(x2==y2);
System.out.println(x3==y3);
System.out.println(x4==y4);
}
}
Output:
true
false
true
false
package langpack;
System.out.println(x1==y1);
System.out.println(x2==y2);
System.out.println(x3==y3);
System.out.println(x4==y4);
}
}
Output:
false
true
true
true
Overloading with respect to Autoboxing,
widening and var-arg methods:
Case1: autoboxing v/s widening:
package langpack;
Output:
Widening
package langpack;
Output:
Widening
package langpack;
Output:
Autoboxing
Note:
While resolving overloaded methods, compiler always gives the priority in the
following order:
1. Widening
2. Autoboxing
3. Var-arg methods
Case4:
package langpack;
Output:
Case5:
package langpack;
Output:
Case6:
package langpack;
Output:
Long
Case7:
package langpack;
Output:
Object version
Object version
Autoboxing widening
Case8:
package langpack;
Autoboxing widening
r1
lalit
r2
package langpack;
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
} outpue:
true
true
2. If two objects are not equal by (==) operator then we can’t conclude
anything about .equals() method. It may returns true or false, i.e
package langpack;
System.out.println(s1==s2);
}
}
Output:
False
package langpack;
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
true
package langpack;
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
Output:
True
False
package langpack;
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
Output:
True
True
4. If two objects are not equal by .equals() method then these objects are
always not equal by (==) operator.
If r1.equals(r2) is false then r1==r2 is always false.
package langpack;
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
Output:
False
False
package langpack;
System.out.println(s1.equals(s2));
// System.out.println(s1==s2);
}
}
Output:
False
If argument type is different and content is different then .equals()
method gives false.
package langpack;
System.out.println(s1.equals(s2));
// System.out.println(s1==s2);
}
}
Output:
False
package langpack;
// System.out.println(s1.equals(s2));
System.out.println(s1==s2);
}
}
Output:
false
false
false
true
In general we can use (==) operator for reference comparison and .equals()
method for content comparison.
Note:
Example:
package langpack;
}
}
Output:
false
false
hashCode() method:
Hashing related data structure follows the following fundamental rule:
package langpack;
System.out.println(s1.equals(s2));
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
Output:
true
73184482
73184482
System.out.println(sb1.equals(sb2));
System.out.println(sb1.hashCode());
System.out.println(sb2.hashCode());
}
}
Output:
false
366712642
1829164700
package langpack;
}
}
Output:
true
102737181
102737181
Clone() method:
1. The process of creating exactly duplicate object is called cloning.
2. The main purpose of cloning is to maintain backup copy and to preserve
state of an object.
3. We can perform cloning bys using clone() method of object class.
package langpack;
int i = 20;
int j = 10;
t2.i = 222;
t2.j = 333;
Output:
20 10
222 333
c c
j = 10 ; j = 10;
c c
j = 10 ; j = 10;
d1 d2
d1 d2
package langpack; }
}
public class ShallowCloning {
package langpack;
public static void main(String[] args)
throws CloneNotSupportedException { public class DeepCloning {
Cat c = new Cat(10);
Dog d1 = new Dog(c, 20); public static void
main(String[] args) throws
System.out.println(d1.j + " " + d1.c.i); CloneNotSupportedException {
Cat c = new Cat(10);
Dog d2 = (Dog)d1.clone(); Dog d1 = new Dog(c,
20);
d2.j = 888;
d2.c.i = 999; System.out.println(d1.j +
" " + d1.c.i);
System.out.println(d1.j + " " + d1.c.i); Dog d2 =
(Dog)d1.clone();
System.out.println(d2.j + " " + d2.c.i); d2.j = 888;
} d2.c.i = 999;
} System.out.println(d1.j +
" " + d1.c.i);
System.out.println(d2.j +
" " + d2.c.i);
}
Output:
}
20 10
Exception in thread "main" Output:
java.lang.CloneNotSupportedException:
langpack.Dog 20 10
at java.lang.Object.clone(Native Method) 20 10
at langpack.Dog.clone(Dog.java:13) 888 999
at
langpack.ShallowCloning.main(ShallowClonin
g.java:9)
package langpack;
System.out.println(s6==s8);
}
}
Output:
false
false
true
true
false
true
true
heap SCP
S3 You cannot change me
S1 You cannot change me S4
S5 s9
S6 s8
package langpack;
String s3 = "lalit";
System.out.println(s2==s3);
}
}
Output:
false
true
heap SCP
S1 lalit S2 lalit
S3
package langpack;
String s4 = "lalitbizlain";
System.out.println(s3==s4);
System.out.println(s2==s3);
}
}
Output:
lalitbizlain
lalitbizlain
false
true
true (false aana chahiye)
false
Heap SCP
S1 lalit lalit
S2 lalitbizlain bizlain
S3 lalitbizlain
S4
S5 lalitbizlain
Questions:
Answer:
String is the most commonly object and hence SUN People provided
special memory management for String objects but strinBuffer is not commonly
used object and hence special memory management is not required for
StringBuffer.