Wrapper Classes - Parse & ValueOf
parse methods are more commonly used for parsing simple primitive values from
strings.
valueOf methods are useful when
- you need to handle cases where the input can be
nullor - when you want to work with wrapper objects.
Difference between parse and valueOf Methods
Both parse and valueOf methods are used to convert Strings (textual
representations)
of primitive data types or objects into their respective Java types.
However, there are some differences between the two methods:
-
Usage:
-
parsemethods are usually static methods defined in primitive wrapper classes (Integer,Double, etc.) and thejava.timeclasses for parsing date and time formats. -
valueOfmethods are usually static methods defined in primitive wrapper classes (Integer,Double, etc.), and they return the respective wrapper object. They are also present in some other classes likeBoolean,BigInteger, andBigDecimal.
-
-
Return Type:
-
parsemethods return the primitive data type corresponding to the parsed value. For example,Integer.parseInt(String)returns anint. -
valueOfmethods return an instance of the corresponding wrapper class. For example,Integer.valueOf(String)returns anInteger.
-
-
Exception Handling:
-
parsemethods may throw aNumberFormatExceptionif the provided string cannot be parsed as the respective primitive type. -
valueOfmethods can returnnullif the provided string cannot be parsed, but they generally don’t throw exceptions.
-
-
Null Handling:
-
parsemethods do not handle null values; passingnulltoparsemethods will result in aNullPointerException. -
valueOfmethods can handlenullby returningnull.
-
-
Usages:
-
parsemethods are commonly used when you expect valid input and want the parsed primitive value directly. For example,Integer.parseInt("123")returns anint. -
valueOfmethods are often used when you want to handle possible null values or if you need to manipulate the parsed value further. For example,Integer.valueOf("123")returns anInteger, which can be assigned to anIntegerreference and can handle null values.
-
Using parse:
int intValue = Integer.parseInt("123");
double doubleValue = Double.parseDouble("3.14");
Using valueOf:
Integer integerObject = Integer.valueOf("123");
Double doubleObject = Double.valueOf("3.14");
Boolean booleanObject = Boolean.valueOf("true");