So I've got a String and I want to create a Double object with the String as a value.
I can call
Double myDouble = new Double (myString);
or I can call
Double myDouble = Double.valueOf(myString);
Is there a difference? I'm guessing the first guarantees a new object is created on the heap and the second might re-use an existing object.
For extra credit: the string might be null, in which case I want the Double to be null, but both the above throw a NullPointerException. Is there a way of writing
Double myDouble = myString == null ? null : Double.valueOf(myString);
in less code?
valueOf() creates a Double object which is often not needed. parseDouble() does not. With autoboxing it's valueOf(String) which is no longer needed, but is therefore backward compatibility.
Returns. a Double object holding the value represented by the String argument.
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.
Java double is used to represent floating-point numbers. It uses 64 bits to store a variable value and has a range greater than float type. Syntax: // square root variable is declared with a double type.
Depends on the implementation. openJDK 6 b14 uses this implementation of Double(String s)
:
this(valueOf(s).doubleValue());
So it calls valueOf(String s)
internally and must be less efficient compared to calling that method directly.
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