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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With