Integer.valueOf() vs. Integer.parseInt()

JavaStringIntegerDecimal Point

Java Problem Overview


Aside from Integer.parseInt() handling the minus sign (as documented), are there any other differences between Integer.valueOf() and Integer.parseInt()?

And since neither can parse , as a decimal thousands separator (produces NumberFormatException), is there an already available Java method to do that?

Java Solutions


Solution 1 - Java

Actually, valueOf uses parseInt internally. The difference is parseInt returns an int primitive while valueOf returns an Integer object. Consider from the Integer.class source:

public static int parseInt(String s) throws NumberFormatException {
    return parseInt(s, 10);
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, radix));
}

public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}

As for parsing with a comma, I'm not familiar with one. I would sanitize them.

int million = Integer.parseInt("1,000,000".replace(",", ""));

Solution 2 - Java

First Question: https://stackoverflow.com/questions/508665/difference-between-parseint-and-valueof-in-java

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

Solution 3 - Java

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

Solution 4 - Java

The difference between these two methods is:

Solution 5 - Java

parseInt() parses String to int while valueOf() additionally wraps this int into Integer. That's the only difference.

If you want to have full control over parsing integers, check out NumberFormat with various locales.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionateiobView Question on Stackoverflow
Solution 1 - JavacorsiKaView Answer on Stackoverflow
Solution 2 - JavaMartijn CourteauxView Answer on Stackoverflow
Solution 3 - JavaJoeView Answer on Stackoverflow
Solution 4 - JavaSachindra N. PandeyView Answer on Stackoverflow
Solution 5 - JavaTomasz NurkiewiczView Answer on Stackoverflow