tags:

views:

97

answers:

3

What's the difference between,

Integer i = new Integer("42");

and

Integer i = Integer.valueOf("42");

Thanks.

+4  A: 

None, take a look at Integer.java:

public static Integer valueOf(String s) throws NumberFormatException {
    return new Integer(parseInt(s, 10));
}

Also, the JavaDoc

daveb
Though it is odd to note that there IS a difference between this and Integer.valueOf(Integer.parseInt(s))... for some strange reason valueOf(String) does not recurse to valueOf(int) which has some instance caching built in. Weird.
PSpeed
If there is no difference then why would be there two ways?
Rohit
they have some little difference
SjB
@Rohit: There is no a difference but we should not know it :) That's an implementation detail.
OscarRyz
+1  A: 

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.

OscarRyz
+2  A: 

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.

Carl Smotricz
You missed FILE_NOT_FOUND in your Boolean example (http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx)
spork