Difference between Integer.parseint and new Integer

What is the difference between Integer.parseInt("5")

and new Integer("5")

. I have seen that both types are used in the code, what is the difference between them?

+3


source to share


2 answers


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.

+15


source


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.

+3


source







All Articles