Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison between variables pointing to same Integer object

Tags:

The output of current program is "Strange". But both the variables share 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"); } 

Output: Strange

like image 846
restrictedinfinity Avatar asked Jun 21 '10 14:06

restrictedinfinity


1 Answers

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 
like image 53
Alexander Pogrebnyak Avatar answered Oct 20 '22 13:10

Alexander Pogrebnyak