简体   繁体   中英

Difference between Integer.parseint vs new Integer

What is the difference between Integer.parseInt("5") and new Integer("5") . I saw that in code both types are used, what is the difference between them?

They use the same implementation :

public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}

The main difference is that parseInt returns a primitive ( int ) while the Integer constructor returns (not surprisingly) an Integer instance.

If you need an int , use parseInt . If you need an Integer instance, either call parseInt and assign it to an Integer variable (which will auto-box it) or call Integer.valueOf(String) , which is better than calling the Integer(String) constructor, since the Integer constructor doesn't take advantage of the IntegerCache (since you always get a new instance when you write new Integer(..) ).

I don't see a reason to ever use new Integer("5") . Integer.valueOf("5") is better if you need an Integer instance, since it will return a cached instance for small integers.

The Java documentation for Integer states :

The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.

So I guess its the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM