Java.lang Package


Introduction:

The most commonly required classes and interface which are needed for casting any java program whether it is simple or complex are encapsulated into a separate package which is nothing but lang package.
It is not required to import lang package explicitly because by default it is available to every java program.


Commonly used classes in lang package:

1) Object
2) String
3) String Builder
4) String Buffer
5) Wrapper classes(auto boxing and autounboxing)

1) Object:
The most common methods which are required for any java object are encapsulated into a separate class which is nothing but object class.
Some people made this class as parent for all java classes so that its methods by default gets available to every java class automatically.
Every class in java is the child class of object either directly or indirectly, if a class extends any other class only then a class is direct child class of object.
Let's see an example:
class A
{

}

If our class extends any other class then our class is not direct child class of object. It extends object class indirectly.

Example

class A extends B
{


}

Object class defines the following methods:
1) public string tostring()
2) public native int hashcode()
3) public boolean equals(Object o)
4) protected native object code() throws CodeNotSupportException
5) public final class getclass()
6) protected void finalize() throws Throwable
7) public final void wait() throws Interrupted Exception
8) public final native void wait(long ms) throws Interrupted Exception
9) public final void wait(long ms,int ns) throws Interrupted Exception
10) public final native void notify()
11) public final native void notifyAll()

1) tostring() method:
We can use this method to find string separations of an object. Whenever we need to print any object reference internally, tostring() method will be executed.
Let's see an example:


In the above case, tostring() method is implemented as follows:


To provide our own String representation, we have to override toString() in our class which is highly recommended.
Whenever we need to print student object reference to return his name and roll number, we have to override toString() as follows:


In StringBuffer and in wrapper classes toString method is overridden to return proper string form.
Hence,it is highly recommended to override toString() method in our class also.
Let's see an example:


2) hashcode():
For every object, JVM assigns one unique id which is nothing but hashcode.
JVM uses hashcode while saving objects into hashtable or hashSet or hashmap.
Based on our requirements, we can generate hashcode by overriding hashcode method in our class.
If we are not overriding hashcode() method method then object class hashcode() method will be executed which generates a hashcode based on the address of the object but whenever we are overriding hashcode() method, hashcode will no longer be related to the address of that object.
Overriding hashcode() method is said to be proper iff for every object we have to generate a unique number.
Let's see an example having two cases:
Case 1:


Case 2:


Case 1: It is an improper way of overriding hashcode() because we are generating some hashcode for every object.
Case 2: It is a proper way to overriding hashcode() because we are generating a different hashcode for every object.

toString vs hashcode:

Example 1:


Example 2:


Example 3:



NOTE:
If we are giving opportunity to object class toString() method then it will call internally hashcode() method.
If we are giving opportunity to over class toString() method then it may not call hashcode() method.

3) equals() method:
We can use equals() method to check equality of two objects.
Let's see an example:


In the above case object class equals() method will be executed which is always must for reference comparison (Address comparison) i.e. if two references are pointing to the same object only then equals() method returns true. This behavior is exactly same as == operator.
If we want to perform content comparison instead of reference compression we have to override equals() method in our classes.

Whenever we are overriding equals() method we have to consider the following things:
1) The meaning of equality.
2) In case of different types of objects (Heterogeneous) equals method should return false but not ClassCastException.
3) If we are passing Null arrangement our equals() method should returns false but not a NullPointerException.

The following way is the valid way of overriding equals() method:



Short way of waiting equals() method:


Relationship between==operators and .equals() method:
If s1==s2 is true, then s1.equals(s2) is always true.
If s1==s2 is false, then we can't tell about s1.equals(s2) exactly. It may return true or false.
If s1.equals(s2) return true, we can't console anything about s1==s2, it will return either true or false.
If s1.equals(s2) is false, then s1==s2 is always false.

Difference between == operators and .equals() method:

==operator
1) It is an operator applicable for both primitives.
2) In case of object reference == operator, if two references are pointing to the same object only then ==operator returns.
3) We can't override ==operator for content Comparision.
4) In the case of heterogeneous type object == operator causes compile time error saying Incomparable types.
(5) For any object reference r, r==null is always false.


.equals()
1) It is a method applicable only for object reference not for primitives.
2) By default .equals() method present in object class is always meant for reference comparision. 3) We can override .equals() method for content comparision.
4) In case of heterogenous objects .equals() method simply returns false and we can't get any compile time or runtime error
5) For any object reference r, r.equals(null) is always false



Note:
What is the difference between double equal operator(==) and .equals()?
'==' operator is always meant for reference comparison where as .equals() method is meant for content Comparison.




Example


In String, .equals() is override for content comparison.
In String Buffer class, .equals() is not overridden for content comparison hence object class .equals() got executed which is meant for reference comparison.
In wrapper class .equals() is overridden for content comparison.

Contract betweent .equals() and hashcode():
1) If two objects are equal by .equals() their hashcode must be same.
2) If two objects are not equal by .equals() then there are no restrictions on hashcode(), it can be same Or different.
3) If hashcodes of two objects are equal, then we can't say about .equals(). It may return true or false.
4) If hashcode and objects are not equal then .equals() always returns false.

Conclusion:
To satisfy the above contract between .equals() and hashcode(), whenever we are overriding .equals() we should override hashcode() also.
If we will not override we won't get any compile time and run-time error.
But it is not a good program practice.

Consider the following .equals()



Which of the following hashcode() are said to be properly implemented?
1) public int hashcode()
{ return 100; //Wrong
}

2) public int hashcode()
{ return age +(int)height; //wrong
}

3) public int hashcode()
{
return name.hashcode() +age; //right
}

4) public int hashcode()
{
return (int)height; //wrong
}

5) public int hashcode()
{
return age +name.length();
}


Note: To Maintain a contract between .equals() and hashcode() what ever the parameters we are using while overriding .equals() we have to use the same parameters while overriding hashcode() also.


Clone():
The process of creating exactly duplicate objects is called cloning.
The main objective of cloning is to maintain backup.
We can get cloned object by using clone() of objects class protected native object clone() throws cloneNotSupportException.



We can call clone() only on cloneable objects.
An object is said to clonable if the corresponding class implements Cloneable interface.
Cloneable interface presently java.lang.package and doesn't contain any methods. It is a marker interface.

Deep Cloning and Shallow Cloning:
The process of creating just duplicate reference variable but not duplicate object is called shallow cloning
The process of creating exactly duplicate independent objects is by default considered as deep cloning.




String class
Case 1:



Once we created a string object we can't perform any changes in the existing object.
If we are trying to perform any changes in the existing object, this behavior is nothing but "immutability of buffer object".


Once we created a StringBuffer object we can perform any changes.
It also changes the new object which we created. It is nothing but "mutability of String object".

getclass(): This method returns run-time class definition of an object Example


Case 2:

In String class, .equals() method is overridden for content comparison. Hence .equals() method returns true if content is same even though objects are different.


In StringBuffer class, .equals() method is not overridden for content comparison. Hence .equals() method will be meant for reference comparison. Due to this, .equals() method returns false even though content is same.

Note:
1) Garbage Collector is not allowed to access in scp area hence even though object doesn't have any reference variable still it is not eligible for Garbage Collector and it is present in scp area.
2) All objects present in scp will be destroyed automatically at the time of JVM shutdown.
3) Object creation in scp is always optional. First Jvm checks if any object is present in scp with required content or not.
If it is already available then it will reuse existing object instead of creating new object.
If it is not already available then a new object will be created. Hence, there is no chance of two objects with the same content in scp i.e. Duplicate objects are not allowed in scp.
Example:



Example:



Note:
1) For every String constant, one object will be created in scp area.
2) Because of same runtime operation if an object is required to creat that object, it should be created only in heap but not in scp.
Example: String s="javat"+new String("javat"); // SCP

Example:


Interning And String:
By using heap object reference if we want to get corresponding scp object reference then we should go for intern().
Example String s1=new String("javat");
If the corresponding object is not available in scp, then intern() creates that object and returns it.

Constructors of the string class:
1) String s=new String();
2) String s=new String(string constant);
3) String s=new String(StringBuffer sb);
4) String s=new String(char[] ch);

5) String s=new String(byte[] b);

Let's see examples


Important methods of string class:
1) public char charAt(int index);
Example:


2) public string concat(string s)
Example:


The overloaded +,+= operators are meant for concatenation only.

3) public boolean equals(Object obj) is meant for content comparison where the case is also important.

4) Public boolean equalIgnoreCase(String s) is meant for content comparison where the case is not important.
Example:



Note:
In general to perfom validation of username we have to go for equalsIgnoreCase method where the case is not important. Where as to perform password validation we have to else quals() where the case is important.


5) public String substring(int begin); references the substring from begining index to end of the string.

6) public String substring(int begin,int end); returns the substring form begining index to end index.
Example:



7) public int length();
Example:



Note:
Length variable is applicable for arrays where as length() is applicable for string objects.


8) public String replace(char old, char new);
Example:


9) public string toLowerCase();
10) public string toUpperCase();
11) public string trim();
To remove the blank space present at beginning and end of the string but not blankspace present at the middle of the string.
12) public int indexOf(char ch);
It returns indexOf first occurence of the specified character.
13) public int lastIndexOf(char ch);




In our program if any string object is required to use separately, it is not recommended to create a separate object for every requirement.
This approach reduces performed & memory utilization.
We can resolve this problem by creating only one object and share the same object with all the required references.
This approach improves memory utilization and performance. We can achieve this by using string constant pool.
In scp, a single object will be shared for all required reference. Hence the main advantages of scp are memory utilization and performances will be improved.
But the problem in this approach is, as several references point to the same object by using one reference, If we perform any changes all remaining references will be improved.
To resolve this some people declare string objects as immutable().
According to that once we create string object we can't perform any changes in the existing object.
If we are trying to perform any changes, there will be no effect on remaining references.
Hence, the main disadvantage of scp is we have to maintain String object as immutable.

Few Questions:

Ques-1. Why scp like concept is defined only for string object but not for StringBuffer?
In any java program,the most commonly used object is string. Hence repeated memory and performances special arrangement is required and for this scp concept is required.
While StringBuffer is commonly used object. Hence special concepts like scp is not required.

Ques-2. What are the advantages of scp? Instead of creating a separate object for every requirement we can create only one object in scp and we can reuse the same object for every requirement.
So that performance and memory utilization will be increased.

Ques-3. What are the disadvantages of scp?
We have to make string object as immutable.

Ques-4. Why string objects are immutable where as StringBuffer object are mutable?
In this case of string several references can point to the same object.
By using one reference, if we are performing any change in the existing object the remaining reference will be affected. So to resolve this problem some people declare string objects as immutable.
Due to this, we created a string object. We can't perform any changes in the existing object.
If we are trying to perform any changes then a new object is created i.e. scp is the only reason.

Ques-5. Why the string object are immutable?
In case of StringBuffer, for every requirement a separate object will be created. By revising the same Stringbuffer, There is no changes In one stringbuffer object if we are performing any changes there is no impact of remaining references. we can perform any changes in the StringBuffer object and StringBuffer objects are mutable.
Ques-6. Is it possible to create our own immutable class?
Yes. Once we create a string object we can't perform any changes in the existing object.
If we are trying to perform any changes then with those changes a new object will be created on the heap.
Because of our runtime method call if there is a change in content only then a new object will be created.
If there is no change in content existing object only will be reused.

Example:


Creation of our own Immutable class:
We can create our own immutable class also.
Once we create an object we can't perform any change in the existing object. If we are trying perform any changes then with those changes a new object will be created.
Because of our runtime method call if there is no change in the content then existing object will be returned.
Example:


Ques: In java which object are immutable?

(1) String objects
(2) All wrapper objects

StringBuffer:
If the content will change frequently then it is never recommended to go for string. Because for every changes compulsory a new object will be created.
To handle this required commpulsary we should go for stringbuffer where all changes will be performed in existing object only instead of creating new object.

Constructor:
1) StringBuffer sb=new StringBuffer();
Create an empty stringbuffer object with default initial capacity
Once stringbuffer reaches its maximum capacity a new sb object will be created with New capacity=(current capacity+1)*2
Example:


2) StringBuffer sb=new StringBuffer(int initialcapacity);
Create an empty sb object with specified initial capacity.

3)StringBuffer sb=new StrinBuffer(String s);
Create an equivalent SB object for the given string with capacity=16+s.lenght();

Important methods & StringBuffer class:
1) public int length()
2) public int capacity()
3) public class charAt(int index);
Example:


4) public void setcharAt(int index,char ch);
To replace the character locating at specified index with the provided character.

5) public StringBuffer append(String s);
append(int i);
append(boolean b); // this method and other two methods have been overloaded
append(double d); //overload
append(object o); //overload

Example:


6) public StringBuffer insert(int index,String s);
(int index, int i);
boolean b;
double d;

Example:


7) public StringBuffer delete(int begin,int end);
To delete the characters present at the begining index to end-1 index.

8) public StringBuffer deletecharAt(int index);
To delete the character locating at specified index

9) public StringBuffer reverse()

Example:


10)public void setLength(int length)
Example:


11) public void ensure(int capacity);
To get the capacity based on our requirement

Example:


12) public void trimInSize()
To release extra allocated free memory after calling. In this method length and capacity will be equal.

Example:


StringBuffer:
Every method present in StringBuffer is synchronized. Hence at a time only one thread is allowed to access StringBuffer object. It Increases waiting time of the thread and affects performances of the system.
To resolve this problem some people introduced StringBuffer in 1.5 version.
StringBuffer is exactly same as StringBuffer(including method and constructor) except the following difference.

StringBuffer
1) Every method is synchronized.
2) SB object is thread safe.
3) Relatively performance is low.
4) Introduced in 1.0 version.

StringBuilder
1) No method is synchronized.
2)String builder is not thread safe.
3) Relatively performance is high.
4) Introduced in 1.0 version.

String vs StringBuffer vs StringBuilder:
1) If the content will not change frequently then we should go for String.
2) If the content will change frequently and thread Safety is required then we should go for StringBuffer.
3) If the content will change frequently and thread safety is not required then we should go for StringBuilder.

Method Chaining:
For most of the methods in string, StringBuffer and StringBuilder the return type is of same type only. Hemce after applying a method the result is we can call another method that forms method chaining
Sb.m1()..m2()...m3()...m4().....
In mehod chaining all methods will be executed form left to right.
Example:


Final vs Immutable:
If a reference variable declared as the final then we can't reassign that reference variable to some other object.
Example:


Declaring a reference variable as final, we want to get any immutability. In the corresponding object we can perform any type of change eventhough reference variable is declared as final.
Example:


Output: javatlearning

Hence final variable and immutability both concepts are different.
Wrapper classes:
The main objectives of wrapper classes are:
(I) To wrap primitives into object form so that we can handle primitive just like objects.
(II) To define several utility methods for the primitives.
Constructor of wrapper classes: Creation of wrapper object:
Almost all wrapper classes contain two constructors.

One can take corresponding primitives as arguments and the others can take string as arrangements.
Example:


Example:


->If the string is not properly formatted then we will get Run Time Error saying NumberFormatException.

Example:


Output: Run Time Error -> Float class contain 3 constructors one can take float primitives and the other can take string and 3rd one can take double arguments. Example:


Character class contains only one constructor which can take char primitive as arguments.

Example:


Boolean class contains two constructors one can take Boolean primitive as the arguments and the other can take string as arguments.
If we are passing Boolean primitive as arguments the only allowed values are true, false.
By mistake if we providing any other value we will get compile time error.

Example:


If we are passing string arguments to the Boolean constructors then the case is not important and content is also not important.
If the content case is insensitive string then it is true, otherwise it is treated as false.

Example:


Wrapper classes:


1) Byte
2) Short
3) Integer
4) Long
5) Float
6) Double
7) character
8) Boolean
Corresponding constructor argument:
1) byte as string
2) Short as string
3) int as string
4) long as string
5) float or string or double
6) double or string
7) char
8) Boolean or string


Let's see which one is true and which one is false:



Notes:
-> In every wrapper class toString() is overridden to return its contents.
-> In every wrapper class .equals() is overridden for content comparison.

Utility Method:
There are four methods:

(I) valueOf()
(II) xxxvalue()
(III) parsevalue()
(IV) toString()
(I) valueOf:
-> We can use value of method for creating wrapper object asan alternative to constructor:
Form 1:
->Every wrapper class contains a static valueOf() method for converting string to the wrapper object.
public static wrapper valueOf(String s)
Example:


Form 2:
-> Every integer type wrapper class(Byte.shrt.Integer.lang) contains the following valueOf() method to convert specified Radix String form to corresponding wrapper object.
public static wrapper valueOf(String s,int radix);
Example:


Form 3:
Every Wrapper class including character class contains the following valueOf() to convert primitives to corresponding wrapper objects.
Example:


Note:


(II) xxxvalue();
We can use xxxvalue() methods to convert wrapper object to primitives.
Every number type wrapper class contains the following size(6) xxxvalue() methods
->The methods are:
public byte byteValue();
public int intValue();
public short shortValue();
public long longValue();
public float floatValue();
public double doublevalue();

Example:


(a) charvalue():
character class contains char value method to convert character object to the char primitive.
public char charValue();
Example:


(b) BooleanValue():
->Boolean class contains booleanValue to find boolean primitives for the given Boolean object.
Public Boolean booleanValue();
Example:


Note:
Total 38=(6*6*+1+1) xxxValue() are variables.

(III) parsexxx():
We can use parsexxx() to convert string to corresponding primitives.
Form1:
Every wrapper class except char class contains following parsexxx() to,convert string to corresponding primitive.
public static primitive parseXXX(String s);
Example:


Form 2:
Every Integer type wrapper class contains the following parseXXX() to convert specified radix string to corresponging primitive.
Example: public static primitive parseXXX(String s,int radix);




(iv) toString:
We can use tostring() to convert wrapper object or primitive to string
Form 1:
Every wrapper class contains the following tostring() to convert wrapper object to string type.
public string tostring();
It is overriding version of object class tostring()
Example:


Form 2:
Every wrapper class contains a static tostring(), to convert primitive to string form.
public static tostring(primitive p);


Form 3:
Integer and Long classes contains toString() to convert primitive to specified radix string form.
public static string tostring(primitive p,int radix);
Example:


Form 4:
Integer and long classes contains the following toXXXString();
1. public static toBinaryString(primitive p);
2. public static string toOctalString(primitive p);
3. public static string toHexString(primitive p);
Example:


Dancing between String,wrapper object, and primitive value:





1) String,StringBuffer, StringBuilder all wrapper classes are final.
2) The wrapper classes which are not child classes of number, character and Boolean
3) The wrapper classes which are not child classes of object are byte,short,Integer,Long,float,double
4) Sometimes we can consider void also as wrapper classes.
5) In addition to String objects all wrapper objects are Immutable.
Autoboxing and Autounboxing:
Until 1.4 version we can't provide primitive value at the place of wrapper objects and wrapper objects at the place of primitive.
All the required conversion should be performed explicitly by the program.
Example:





But from 1.5 version on words in the place of wrapper object we can provide primitive value and in the place of primitive value we can provide wrapper objects.
All the required conversions will be performed automatically by the compiler. Their automatic conversion are called Autoboxing and Autounboxing.

Autoboxing:
Automatic conversion of primitive value to the wrapper object by compiler is called autoboxing.
Example:


Auto-Unboxing:
Automatic conversion of wrapper object to the primitive type by compiler is called "Auto-Unboxing".

Example:




Example:


i.e. Autoboxing concept is internally implemented by using valueOf()
Example:


i.e. Autounboxing concat is internally implemented by using xxxValue().

Example:



Note:
Because of autoboxing and Auto-unboxing from 1.5 version onwards there is no diff between primitive value and wrapper objects. We can use interchanging.


Example:



Note: Because if we want to change after creating an object then that few changed object is created with the same reference name


Example:


Example:


Example:


Example:


Example:


Conclusions:
By autoboxing if an object is required to create and compiler wants to create that object immidiately, first he should check is there any object already created.
If it is already created then it will reuse existing object instead of creating the new one.
If it is not already there, then only a new object will be created .
But this rule is applicable only in the following cases:
1) Byte->Always
2)Short-> -128 to 127
3)Integer-> -128 to 127
4) Long-> -128 to 127
5) Character -> 0 to 127
6) Boolean->always
Except the above range in all other cases, a new object will be created.

Example:


Case 1: Widening vs Auto-boxing:


Widening dominates Auto-boxing:
Case 2:
Widening vs var-arg():

Example:


Widening dominates var-arg()
Case 3: Auto-boxing vs var-arg:

Example:


In general var-arg() will get least priority, if no other method matches only then var-arg() will be executed.
While resolving overloaded methods compiler will always keep the precedence in the following order:
(I) Widening
(II) Auto-boxing
(III) Var-arg()

Case4:





Compile time Error:
M1(java.lang.long) in test cannot be applied to(int)
Widening followed by auto-boxing which is not allowed in java where as autoboxing followed by widening is allowed.

Example: