What's the difference between calling Double.valueOf(String s) and new Double(String s)?
Your assumption is right. The second way of getting a Double out of String can be faster because the value may be returned from a cache.
Regarding the second question, you may create a helper null safe method which would return a null instead of throwing NullPointerException.
from apache
public static Double valueOf(String string) throws NumberFormatException {
return new Double(parseDouble(string));
}
&
public Double(String string) throws NumberFormatException {
this(parseDouble(string));
}
from sun[oracle ] jdk
public Double(String s) throws NumberFormatException {
// REMIND: this is inefficient
this(valueOf(s).doubleValue());
}
&
public static Double valueOf(double d) {
return new Double(d);
}
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.