Java – why do you return false and true?
public class Test {
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); } }
Solution
edit
The ternary operator executes some type conversions under the hood In your case, you mix primitive and wrapper types. In this case, the wrapper type is unboxed, and then the result of the ternary operator is "repacked":
So your code is basically equivalent to (except for the error that longvalue should be doublevalue):
public static void main(String[] args){ Double d = 12.0; System.out.println(d == DEFAULT_DOUBLE); Long l = 1L; System.out.println(l == DEFAULT_LONG); }
Long values can be cached on some JVMs, so the = = comparison can return true If you do all the comparisons using equals, you will get real results in both cases
Note that if you use public static final long default_ LONG = 128L; And try:
Long l = 128L; System.out.println(l == DEFAULT_LONG);
It may print false because long values are usually cached only between - 128 and 127
Note: JLS requires to cache char, byte and int values between - 127 and 128, but do not say anything long Therefore, your code may actually print false twice on different JVMs