EDIT
The ternary operator does some type conversions under the hood . In your case, you mix the primitives and types of wrappers, and in this case the types of wrappers are unpacked, then the result of the triple operator "re-boxed":
If one of the second and third operands has a primitive type T, and the type of the other is the result of applying the conversion of the box (section 5.1.7) to T, then the conditional expression type is T.
So your code is essentially equivalent (except for a typo where 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, and comparing == can therefore return true. If you did all the comparisons with equals , you would get true 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 will probably print false, since long values are usually cached between -128 and +127.
Note. JLS requires that the char , byte and int values between -127 and +128 be cached but does not say anything about long . That way, your code can actually print false twice on another JVM.
source share