Member-only story
An Interesting Interview Question: What’s the Difference Among new Integer(“127”), Integer.valueOf(“127”) and Integer.valueOf(“128”)?
My articles are open to everyone; non-member readers can read the full article by clicking this link.
Did you think it was so easy when you saw this question? I wonder if you can answer it easily. 😊
Actually, this question involves a subtlety in the creation and caching mechanism of the Integer object in Java. It’s a seemingly basic problem but is easy to overlook.
First of all, let’s take a look at a piece of code and then conduct a specific analysis.
Integer a = new Integer("127");
Integer b = new Integer("127");
System.out.println(a == b); // false
Integer c = Integer.valueOf("127");
Integer d = Integer.valueOf("127");
System.out.println(c == d); // true
Integer e = Integer.valueOf("128");
Integer f = Integer.valueOf("128");
System.out.println(e == f); // false
Main Differences
1. Object Creation
Both new Integer
and Integer.valueOf
methods will create new objects.
However, new Integer
will create a new object every time, while Integer.valueOf
will create an object based on the cache hit situation.