Tuesday, June 14, 2016

Integer , Long, Float, Dobule comparision

public class MyTestClassForInteger {
    public static void main(String[] args) {
        Integer i=10;
        Integer j=10;

        Integer k=100;
        Integer l=100;
        System.out.println(i==j);
        System.out.println(i==j);
    }
}
But the question is how compiler see this code . It compiles and make the above code as below 
After complication the code becomes as follows in MyTestClassForInteger.class file
public class MyTestClassForInteger {
    public MyTestClassForInteger() {         /// Fist difference - compiler adding a defualt constructor.
} public static void main(String[] args) { Integer i = Integer.valueOf(10); //// This is the second difference its calling valueof(int i) method of Integer Class to get the value. Integer j = Integer.valueOf(10); Integer k = Integer.valueOf(100); Integer l = Integer.valueOf(100); System.out.println(i == j); System.out.println(i == j); } }

Now look into Integer class .  Yo will see this 
1:public static Integer valueOf(int i) {
2:      final int offset = 128;
 3:      if (i >= -128 && i <= 127) { // must cache
 4:       return IntegerCache.cache[i + offset];
5:       }
6:      return new Integer(i);
7:   }
Inside method at line 3 first its checking value of i whethere its in between a range or not. then if its true its goes to line 4
Now at line 4 there is another class IntegerCache  . This is the static class inside Integer class. This class is declaring an 
array of size 256 which is storing value from -128 to 127. its like Integer cache[]={-128,-127,-126.....0,1.....127};
All these things are happening at the time of start of JVM and before even using of Integer anywhewre
You can say that value of -128 to 127 of int is already cached and present in cached array.
Whenever we are using Integer it's valueOf(int i) method is returning value from cache without creating any 
new Intger object (line nuumber 6).  But if value go beyond 127 or less than -128 then its creating a new object and returning 
a new intger object.
The purpose of putting int value from -128 to 127 into cache array is to improve performance. Because we heavling use int in that range .
It was the assumption made by JDK developers and I do not think its very good idea.
Thats why it it returing true for 10, 100 but not for 1000 because objects are not equal using == operator.

In Case of Long:
Same rule apply as above. Seee the valueOf(long L);
In case of Double , Float:   They will never be true in == comparision because they do not cache any value and 
they are returning a new object each time   valueOf(double d);

No comments:

Post a Comment