Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
What is the difference between parseXxx() and valueOf()?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: What is the difference between parseXxx() and valueOf()?

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.


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help