I want to convert String
to a Double
data type. I do not know if I should use parseDouble
or valueOf
.
What is the difference between these two methods?
Double parseDouble() method in Java with examples The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double.
Returns. a Double object holding the value represented by the String argument.
Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.
parseDouble
returns a primitive double containing the value of the string:
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
valueOf
returns a Double instance, if already cached, you'll get the same cached instance.
Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values.
To avoid the overhead of creating a new Double object instance, you should normally use valueOf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With