What is the difference between parseXxx() and valueOf()?
The parseXxx() methods and the valueOf() methods are defined in most of the numeric primitive wrapper classes, such as Integer, Long, Double, FLoat, etc.
Both methods take a String argument and convert it into the corresponding primitive type with the value that the String represents. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. If the String argument is not properly formed, both throws a NumberFormatException.
The biggest difference between these two methods is that:
- parseXxx() returns the primitive type;
- valueOf() returns a wrapper object reference of the type.
Let's take a look at the following examples:
int i = Integer.parseInt("100"); // the result is 100
Integer i = Integer.valueOf("100"); // create a Integer object with value 100
double d = Double.parseDouble("12.34");
Double d = Double.valueOf("12.34");
Both methods has a overloaded counter part, which takes a radix as the second argument. The methods that doesn't takes the radix as the second argument, uses 10 as the radix. For example:
long l = Long.parseLong("10101010", 2); // binary String to long, the value is 170
Long l = Long.valueOf("10101010", 2); // created a Long object with value 170
Please see How to convert String to primitive type value? for more examples to convert String to numeric types.
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- What are class variables in Java?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?
- How to Use JDBC Java to Create Table?
- Why final variable in Enhanced for Loop does not act final?