What's the difference between,
Integer i = new Integer("42");
and
Integer i = Integer.valueOf("42");
Thanks.
What's the difference between,
Integer i = new Integer("42");
and
Integer i = Integer.valueOf("42");
Thanks.
None, take a look at Integer.java:
public static Integer valueOf(String s) throws NumberFormatException {
return new Integer(parseInt(s, 10));
}
Also, the JavaDoc
Looking at the source code we can tell there is no difference.
The former creates a new integer using the constructor explicitly.
The later creates an integer using a factory method ( which turns out to call the constructor ).
The fact the second calls the first, is an implementation detail and not necessarily true in all the implementations, in some cases it may not call the constructor but use a cache ( as in valueOf( int i )
)
The resulting Integer behaves exactly the same in both cases.
Yet, nothing prevents from changing the second to:
public static Integer valueOf(String s, int radix) throws NumberFormatException {
return valueOf( parseInt( s, radix ));// which uses the cache
}
That change can be performed in the next release ( or perhaps some VM does it that way ) and your code would get it "automatically" in the upgrade, while in the other hand, using the constructor you can't, because well, you're invoking the constructor explicitly.
Using new
very unambiguously demands the creation of a new object for every occurrence.
Using the factory pattern (valueOf
) gives the implementation a chance (which it needn't accept) to instead provide an already created instance from cache.
I've heard some implementation cache the first 100 or so Integers because they occur frequently enough for this to pay off.
The case where this is most useful is with Boolean
. We KNOW there are only two possible distinct values, so valueOf
always returns one of those two without the overhead of creating a new object. Using new
with Boolean is legal but will always incur an overhead in performance and memory use.