0

I have written the following code in JAVA,

Integer i=10;
Integer i1=10;
s.o.pln(i==i1);//true
Integer j=100;
Integer j1=100;
s.o.pln(j==j1);//true
Integer k=1000;
Integer k1=1000;
s.o.pln(k==k1);//false

Here, as Integer is a wrapper class, It must show true to all the declared types. But it is showing false for 1000.

Can someone explain the reason behind it.

srikar
  • 1
  • 1
    This is because, if I am not mistaken, the JRE (at least Oracle's) has a cache of all `Integer`s between -128 and 127 or something like that – fge Apr 14 '14 at 11:56
  • "It must show true to all the declared types" <-- _absolutely not_. An `Integer` is not an `int`. What you do here is compare _references_. An `Integer` will be "auto unboxed" to an int _if and only if_ one member of the equal operator is an `int`. Try with `int k1 = 1000;`. – fge Apr 14 '14 at 11:58

1 Answers1

2

First, note that when applied to objects (like Integer), the == operator compares references.

Next, note that these assignments imply boxing conversions (also called 'autoboxing') from type int (primitive) to Integer (object).

And according to Java Specification - Conversions

"If the value being boxed is ... an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2."

DanW
  • 247
  • 1
  • 9