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);
}
}
The true operator returns the bool value true to indicate that its operand is definitely true. The false operator returns the bool value true to indicate that its operand is definitely false. The true and false operators are not guaranteed to complement each other.
Because they don't represent equally convertible types/values. The conversion used by == is much more complex than a simple toBoolean conversion used by if ('true') . So given this code true == 'true' , it finds this: "If Type(x) is Boolean , return the result of the comparison ToNumber(x) == y ."
During form submission, if a particular entry is unfilled, return false is used to prevent the submission of the form.
It can return one of the two values. It returns True if the parameter or value passed is True. It returns False if the parameter or value passed is False.
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":
If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.
So your code is essentially equivalent to (apart from the 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 the ==
comparison can therefore return true. If you made 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, because Long values are generally cached between -128 and +127 only.
Note: The JLS requires that char
, byte
and int
values between -127 and +128 be cached but does not say anything about long
. So your code might actually print false twice on a different JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With