Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Integer.parseint vs new Integer

Tags:

java

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?

like image 667
Java Kid Avatar asked Jun 29 '15 12:06

Java Kid


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

like image 77
Eran Avatar answered Sep 23 '22 21:09

Eran


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.

like image 28
Sharon Ben Asher Avatar answered Sep 19 '22 21:09

Sharon Ben Asher