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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With