Archive
Archive for August, 2012
Why Integer Object will behave like this?
August 11, 2012
Leave a comment
Integer i1 = 127; Integer i2 = 127; System.out.println(i1==i2); System.out.println(i1.equals(i2)); Integer i1 = 128; Integer i2 = 128; System.out.println(i1==i2); System.out.println(i1.equals(i2));
O/P
true , true, false ,true
Have you wondered by seeing the output, it should be false, true, false, true right?
But if you run the code it gives the out put as true, true, false, true.
why because Integer object have cache values between -128 to 127.
So first it will be true in the case of 127 as it is in the range of cached values.
But latter case if false as 128 wont fall under the cached values.
http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28int%29
Categories: Java