In an interview, one of my friends was asked: If we have two Integer objects, Integer a = 127; Integer b = 127;
Why does a == b
evaluate to true
when both are holding two separate objects? In this article, I will try to answer this question and explain the answer.
You may also like: The Internal Cache of Integers
Short Answer
The short answer to this question is, direct assignment of an int
literal to an Integer
reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts Integer a = 127;
to Integer a = Integer.valueOf(127);
.