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
null
or - 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:
-
parse
methods are usually static methods defined in primitive wrapper classes (Integer
,Double
, etc.) and thejava.time
classes for parsing date and time formats. -
valueOf
methods 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:
-
parse
methods return the primitive data type corresponding to the parsed value. For example,Integer.parseInt(String)
returns anint
. -
valueOf
methods return an instance of the corresponding wrapper class. For example,Integer.valueOf(String)
returns anInteger
.
-
-
Exception Handling:
-
parse
methods may throw aNumberFormatException
if the provided string cannot be parsed as the respective primitive type. -
valueOf
methods can returnnull
if the provided string cannot be parsed, but they generally don’t throw exceptions.
-
-
Null Handling:
-
parse
methods do not handle null values; passingnull
toparse
methods will result in aNullPointerException
. -
valueOf
methods can handlenull
by returningnull
.
-
-
Usages:
-
parse
methods are commonly used when you expect valid input and want the parsed primitive value directly. For example,Integer.parseInt("123")
returns anint
. -
valueOf
methods 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 anInteger
reference 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");