public class Test {
public static final Double DEFAULT_DOUBLE = 12.0;
public static final Long DEFAULT_LONG = 1L;
public static Double convertToDouble(Object o) {
return (o instanceof Number) ? ((Number) o).doubleValue()
: DEFAULT_DOUBLE;
}
public static Long convertToLong(Object o) {
return (o instanceof Number) ? ((Number) o).longValue() : DEFAULT_LONG;
}
public static void main(String[] args){
System.out.println(convertToDouble(null) == DEFAULT_DOUBLE);
System.out.println(convertToLong(null) == DEFAULT_LONG);
}
}
public class Test { public static final Double DEFAULT_DOUBLE = 12.0; public static final
Share
EDIT
The ternary operator does some type conversions under the hood. In your case you are mixing primitives and wrapper types, in which case the wrapper types gets unboxed, then the result of the ternary operator is “re-boxed”:
So your code is essentially equivalent to (apart from the typo where
longValueshould bedoubleValue):Long values can be cached on some JVMs and the
==comparison can therefore return true. If you made all the comparisons withequalsyou would gettruein both cases.Note that if you use
public static final Long DEFAULT_LONG = 128L;and try:It will probably print false, because Long values are generally cached between -128 and +127 only.
Note: The JLS requires that
char,byteandintvalues between -127 and +128 be cached but does not say anything aboutlong. So your code might actually print false twice on a different JVM.