There are three ways to convert a String to double value in Java,
Double.parseDouble() method,
Double.valueOf() method and by using
new Double() constructor and then storing resulting object into a primitive double field, autoboxing in Java will convert Double object to double primitive in no time. Out of all these methods, the core method is
parseDouble() which is specially designed to parse an String containing floating point value into Double object. Rest of the methods e.g.
valueOf() and constructor uses
parseDouble() internally. This method will throw
NullPointerException if the string you are passing is null and
NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters. Some of you might be curious and thinking if one method can do the job then why we have three methods for String to Double or double conversion? Well, their purpose is little bit different and they also provide some other service. For example, you should be using
Double.valueOf() method if you frequently need to convert String to Double because it will likely give better performance by caching frequently used values just like
Integer.valueOf() method does. On the other hand if you use
new Double(String value) constructor then you will always get a new Double object, creating memory pressure for your application. BTW, in this article we will not only learn
how to convert String to double value but also how to convert Double to String, as its important to know both side conversion. If you are not looking to convert String to double but to format double values to String, then please check my earlier post,
formatting floating point numbers in Java.