java - Why does this return false and true? -
public class test { public static final double default_double = 12.0; public static final long default_long = 1l; public static double converttodouble(object o) { homecoming (o instanceof number) ? ((number) o).doublevalue() : default_double; } public static long converttolong(object o) { homecoming (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); } }
edit
the ternary operator some type conversions under hood. in case mixing primitives , wrapper types, in case wrapper types gets unboxed, result of ternary operator "re-boxed":
if 1 of sec , 3rd operands of primitive type t, , type of other result of applying boxing conversion (§5.1.7) t, type of conditional look t.
so code equivalent (apart typo longvalue
should 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 cached on jvms , ==
comparing can hence homecoming true. if made comparisons equals
true
in both cases.
note if utilize public static final long default_long = 128l;
, try:
long l = 128l; system.out.println(l == default_long);
it print false, because long values cached between -128 , +127 only.
note: jls requires char
, byte
, int
values between -127 , +128 cached not long
. code might print false twice on different jvm.
java
No comments:
Post a Comment