Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between calling Double.valueOf(String s) and new Double(String s)?

Tags:

java

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?

like image 815
Rob Gilliam Avatar asked Jan 21 '11 11:01

Rob Gilliam


People also ask

What is the difference between double valueOf and double parseDouble?

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.

What is double valueOf?

Returns. a Double object holding the value represented by the String argument.

What does double parse double do?

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.

What is double method in Java?

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.


1 Answers

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.

like image 64
Andreas Dolk Avatar answered Oct 24 '22 16:10

Andreas Dolk