Java Kid
Java Kid

Reputation: 99

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?

Upvotes: 6

Views: 4214

Answers (2)

Eran
Eran

Reputation: 393781

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.

Upvotes: 24

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

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.

Upvotes: 4

Related Questions