We can directly do the following conversion:
String s="123";
int a=new Integer(s);
Then what are the advantages to using Integer.parseInt() method?
Integer constructor internally calls parseInt, which returns int. If you call the parseInt directly you avoid autoboxing (constructor returns Integer).
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
Also using parseInt you can parse the String using different radix than 10. For instance:
int hex = Integer.parseInt("FF", 16); // 255
int bin = Integer.parseInt("10", 2); // 2
In your example you do (implicitly) one additional boxing operation (to an Integer object) which you avoid when using Integer.parseInt. Integer.parseInt just directly gives you an int from your input String.
Basically your code is equivalent to:
String s = "123";
int a = (new Integer(s)).intValue();
As you see, you actually don't need that new Integer(s) object,
all you need is the primitive int value stored it in.
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