1

I am confused with the below code segment.

    Integer i1 = 1000;
    Integer i2 = 1000;
    if(i1 != i2) System.out.println("i1 and i2 are different objects");
    if(i1.equals(i2)) System.out.println("meaningfully equal");

    Integer i3 = 10;
    Integer i4 = 10;
    if(i3 == i4) System.out.println("i3 and i4 Same object");
    if(i3.equals(i4)) System.out.println("meaningfully equal");

Output is:

i1 and i2 are different objects

meaningfully equal

i3 and i4 Same object

meaningfully equal

My question is why i1 and i2 is showing as different objects where the i3 and i4 are not.

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44

1 Answers1

0

Got it. I did not notice the range

In order to save memory, two instances of the

following wrapper objects (created through boxing) will always be == when their

primitive values are the same:

■ Boolean

■ Byte

■ Character from \u0000 to \u007f (7f is 127 in decimal)

■ Short and Integer from –128 to 127

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44