Possible Duplicate:
Wrapper class and == operator
Hi when I am comparing Integer with == I have some problem so
can you explain me why second test is success too ?
@Test
public void integerTest() {
Integer prvni = 127;
Integer druhy = 127;
Integer treti = 128;
Integer ctvrty = 128;
assertTrue(prvni == druhy);
assertTrue(treti != ctvrty);
}
When using
==to compare Objects, you’re actually comparing the references. I.e., the reason both assertions are true is because theprvnianddruhyrefer to the same object whiletretiandctvrtydoes not.This is because the JVM caches
Integerobjects in the range -128 to 127, and reuses cached objects when autoboxing the values.Unless you switch to
intinstead, you could go throughprvni.intValue()or useprvni.equals(...)instead.