I’ve been experimenting with the ternary operator (? :
) in Java and noticed that it automatically performs type casting on its expressions. For example, this code returns 2.0
instead of 2
:
System.out.println(false ? 1.0 : 2);
In a regular if-else
conditional, Java obviously doesn’t perform type casting in the same way, but with the ternary operator, it does.
To determine the resulting type, I used the getClass()
method for cases like differentiating between int
and byte
. For float
or double
versus int
, the difference is obvious, as values like 2
become 2.0
.
This raises a couple of questions:
-
Why does the Java ternary operator perform type conversion in the first place?
-
The operator seems to follow a typical Java type promotion hierarchy (e.g.,
byte -> short -> int -> long -> float
). However, whenint
is involved, it always returns the other type if theint
fits within the range of that type. For example, in the code below, the result is abyte
with the value of1
:
System.out.println(true ? (int) 1 : (byte) 2);
This also applies to short
in similar scenarios.
I haven’t tested all possible type combinations with the ternary operator, but sometimes the type casting behavior seems inconsistent or arbitrary.
How does Java decide which type to return in these cases?
You need to sign in to view this answers