Difference between Integer.parseint and new Integer
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 it parseInt
returns a primitive ( int
), while a constructor Integer
returns (not surprisingly) an instance Integer
.
If you need int
, use parseInt
. If you need an Integer instance, call parseInt
and assign it to an Integer variable (which will be automatically placed in the field), or call Integer.valueOf(String)
, which is better than calling a constructor Integer(String)
, since no constructor Integer
is used IntegerCache
(since you always get a new instance when you write new Integer(..)
).
I see no reason to use new Integer("5")
. Integer.valueOf("5")
it's better if you want an instance Integer
, as it will return a cached instance for small integers.
source to share
The Java documentation for Integer says:
The string is converted to an int value, just like the parseInt method for radix 10.
So, I think they are the same.
source to share