Comparing variables pointing to the same Integer object

The output of the current program is "Strange". But both variables have the same reference. Why are the second and third comparisons 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"); } 

Exit: Strange

+16
java integer
Jun 21 2018-10-21T00:
source share
2 answers

What is the artifact of autoboxing and the fact that Integer is immutable in Java.

a++ and a-- translated something like this.

 int intA = a.getInt( ); intA++; a = Integer.valueOf( intA ); // this is a reference different from b 
+19
Jun 21 '10 at 14:11
source share
β€” -
  • Strage - Obviously, two variables point to the same object.

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

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

+6
Jun 21 '10 at 14:20
source share



All Articles