tags:

views:

75

answers:

2

The ourput of current program is "Strange". But the both the variables share the same reference why are second and thrid comparison not true.

Integer a;
Integer b;
a = new Integer(2);
b = a;
if(b == a) {
    System.out.println("Strange");
}
a++;
if(b == a) {
    System.out.println("Stranger");
}
a--;
if(b == a) {
    System.out.println("Strangest");
}

Output: Strange

+10  A: 

That's the artifact of autoboxing and a fact that Integer is immutable in Java.

The a++ and a-- are translated to roughly this.

int intA = a.getInt( );
intA++;
a = Integer.valueOf( intA ); // this is a reference different from b
Alexander Pogrebnyak
Note that if you replace `a = new Integer(2)` with `a = Integer.valueOf(2)`, "Strangest" will also be printed since it will use the integer cache for getting the instance.
Mark Peters
What do you mean by integer cache in your comment. can you elaborate ?
restrictedinfinity
@restrictedinfinity. At least in Sun's Java, Byte, Short and Integer have a cache of 256 values ranging from -128 to 127 inclusive that are served by `Type.valueOf( )` method. So in our case after `a--` the int value is `2` and that would be the same that we have started with, so `Integer.valueOf( 2 )` would have returned the same `Integer` object. Note, that `Long` type does not have a cache, therefore `Long.valueOf` always returns a new object.
Alexander Pogrebnyak
+3  A: 
  • Strage - it's obvious, the two variables point to the same object

  • not Stranger because of autoboxing. Integer is immutable, so each operation on it creates a new instance.

  • not Strangest, because of the previous point, and because you have used new Integer(..) which ignores the cache that is used for the byte range. If you use Integer.valueOf(2) initially, then the cached Integers will be used and Strangest will also be printed.

Bozho