1
class G2 {
public static void main(String[] args) 
{   
 Short u = 127;
 Short v = 127;
 System.out.println(u==v);
 System.out.println(u!=v);
 Short u1 = 129;
 Short v1 = 129;
 System.out.println(u1==v1);
 System.out.println(u1!=v1);
}
}

I know that when range is between -128 to 127 == operator matches content or value inside object otherwise object reference code is matched of two objects. Why this kind of implementation is there in JAVA?

2 Answers2

4

Auto-boxing implicitly calls Short.valueOf, which uses cached box instances for small numbers up to 127.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
0

Integer objects with internal value in the range between -128 and 127 are compared with an interned object of the same type and value, therefore a reference comparison yields true.

Ideally, every such comparison would yield true, but it is not feasible in practice to keep an object for every possible integer, that's why the Java standard doesn't demand it beyond that point.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104