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.
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