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 avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24746)
- What is runtime polymorphism in Java?(18328)
- How to add BASIC Authentication into HttpURLConnection?(16088)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10446)