parse VS valueOf

In many of the conversions form int to String and String to int or double we suppose to use the Static methods either parse or valueOf for every type. Consider following example,

String str = "900";
int number = Integer.parseInt(str);

In above example we have parsed the String to integer primitive value and for the same task we can also use following way,

String str = "900";
int number = Integer.valueOf(str);

Now, to be more specific in above case we are a victim of one extra auto unboxing in case of valueOf, because valueOf method returns wrapper type not primitive type, while parse method returns primitive type. Even though for invalid input both will fire exception for invalid format.

Now to use both the methods precisely following care should be taken,

String str = "900";
int number = Integer.parseInt(str);
Integer numberW = Integer.valueOf(str);

As it is always good to hold the valueOf result in wrapper and result of parse method in primitive type, to avoid extra overhead of boxing and unboxing.

For example, if you want to return an Integer instead of int as you may want your result to be null instead of 0 you should use valueOf method and at the same time you want to avoid null check you should better work with primitive types.

parse will provide primitive while valueOf will give you wrapper

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s