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?
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)
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