r/javahelp • u/[deleted] • Jun 12 '22
Homework Casting from int to Integer.
So i've been fiddling around with java, and encountered a problem, that I don't quite understand.
int a = 10;Integer bigA = a;Integer bigB = a;System.out.println(bigA == bigB);
This piece of code returns true, for every int below and including 127. Above that it returns false. How so?
17
Upvotes
13
u/DDDDarky Jun 12 '22
When you compare Objects with ==, you basically compare the memory reference. Since Integer objects are often allocated which can have heavy impact on performance, commonly used values (range -128 to 127) are cached, therefore Integers in this range do not allocate new objects, rather take an immutable reference of them, which share the same memory, therefore == will actually work on them.