I am a java novice and so confused by the following example. Is it okay to think that \"==\" sign will compare the values between Integers and \"autoboxed\" Integer
Unboxing will be happing when arithmetic operators
, comparison operators
appear.
eg:
Integer a = 10;
a = a+10; //1.unboxing a to int 2.calculate a+10 3.boxing 20 to Integer.
System.out.print(a > 10); //1.unboxing a to int 2. compare
But when ==
appear, it depends.
If boxing type appear on both side
, it will compare the reference
.But if base type appear on one side
, and the other side is a boxing type, the boxing type will unboxing
to base type.
eg:
Integer a = new Integer(129);
Integer b = new Integer(129);
System.out.println(a == b); // compare reference return false
System.out.println(a == 129); // a will unboxing and compare 129 == 129 return true
PS: In Java.lang.Integer
Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS.
See source code
So:
Integer a = 127;
Integer b = 127; //cached, the same as b a==b return ture
Integer c = 129;
Integer d = 129; // not cached, c==d return false