0

I noticed that the following code returns false

Integer a = 600;
Integer b = 600; 
System.err.println(a == b);

but this one

int a = 600;
int b = 600; 
System.err.println(a == b);

returns true

can anybody explain?

Arno
  • 549
  • 1
  • 4
  • 22

2 Answers2

1

The most important thing to know is the values up to 128 are cached, and the JVM gives you the same objects,for that the reference comparison works. Above 128 it creates a new instance.

For more info go to javadoc of Integer.valueOf(int) (which is what happens behind the scene)

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
0

This behavior is correct, in java == compares object references, it checks to see if the two operands point to the same object (not equivalent objects, the same object).

so your 1st example:

 Integer a = 600;
 Integer b = 600;
 System.err.println(a == b);

you are asking java to tell you if the have the same reference, which is false

in the example 2:

a and b are primitives, and you are asking java to tell you if the have the same value, which is True

Jeff had already an answer for this

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • 1
    `Integer a = 100; Integer b = 100; System.err.println(a == b);` this one returns true – Arno Jan 30 '16 at 09:59