Create objects of wrapper classes with java 9

Viewed 1802

One new feature of Java 9 is to deprecate the constructor of wrapper objects. The only way to create new Wrapper objects is to use their valueOf() static methods. For example for Integer objects, Integer.valueOf implements a cache for the values between -128 and 127 and returns the same reference every time you call it.

As API for Integer class says "The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance." and JLS says "Given a value of the corresponding primitive type, it is generally unnecessary to construct new instances of these box classes. The recommended alternatives to construction are autoboxing or the valueOf static factory methods. In most cases, autoboxing will work, so an expression whose type is a primitive can be used in locations where a box class is required"

But what happens with the values outside this range? For example Integer x = Integer.valueOf(456) is a new object every time the class was executed?

2 Answers

Both

Integer x = Integer.valueOf(456);

and

Integer x = 456;

will always result in a new instance of Integer being created, since 456 is outside the range of the Integer cache.

You can test it by writing

Integer x1 = Integer.valueOf(456);
Integer x2 = Integer.valueOf(456);
System.out.println(x1==x2);

which will print false.

First why bother with these details - the correct way to compare Integer objects is to use either:

if (x.intValue() == y.intValue()) or better x.equals(y)

Don't rely on the fact that there is a cache under any circumstances, since this cache's upper bound can be changed as a property, you can see it via:

java -XX:+PrintFlagsFinal | grep AutoBoxCacheMax
Related