Monday, March 2, 2015

Using == operator in Integer

== operator is working properly with in the integer range.(-128 to 127).

Integer.valueOf() create cache with in the range  (-128 to 127).

Example 1:

Integer i = 127;
Integer j = 127

if(i == j) {
System.out.pritnln("i and j is equal") ;
}else{
System.out.pritnln("i and j is not equal") ;
}
Output: i and j is equal

If integer value is out of this range == operator will not work properly(Its depends on JVM default integerCache).

Example 2:

Integer i = 128;
Integer j = 128

if(i == j) {
System.out.pritnln("i and j is equal") ;
}else{
System.out.pritnln("i and j is not equal") ;
}
Output: i and j is not equal