54
Java Integer Cache — Why Integer.valueOf(127) == Integer.valueOf(127) Is True

Java Integer Cache — Why Integer.valueOf(127) == Integer.valueOf(127) Is True

5 years ago
Anonymous $Dftgs0JzgE

https://medium.com/@njnareshjoshi/java-integer-cache-why-integer-valueof-127-integer-valueof-127-is-true-e5076824a3d5

posted by Naresh Joshi on November 25, 2018

In an interview, one of my friends was asked that if we have two Integer objects, Integer a = 127; Integer b = 127; Why a == b evaluate to true when both are holding two separate objects? In this article, I will try to answer this question and also try to explain the 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);.