October 22, 2024
Chicago 12, Melborne City, USA
java

Why does the conditional (ternary) operator (? :) in Java perform type casting?


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:

  1. Why does the Java ternary operator perform type conversion in the first place?

  2. The operator seems to follow a typical Java type promotion hierarchy (e.g., byte -> short -> int -> long -> float). However, when int is involved, it always returns the other type if the int fits within the range of that type. For example, in the code below, the result is a byte with the value of 1:

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

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video