Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.valueOf() vs. Integer.parseInt() [duplicate]

People also ask

What is the difference between Parse and valueOf in java?

valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer. parseInt(String) . However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int .

What is the use of integer valueOf () function?

valueOf(int a) is an inbuilt method which is used to return an Integer instance representing the specified int value a. Parameters : The method accepts a single parameter a of integer type representing the parameter whose Integer instance is to be returned.

What is use of parseInt () method?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

What is use of valueOf () in java?

The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string.


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(",", ""));

First Question: 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);

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


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.


The difference between these two methods is:

  • parseXxx() returns the primitive type
  • valueOf() returns a wrapper object reference of the type.