The type of a conditional expression — Aptitude Question
The type of a conditional expression: What does this Java program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 105 seconds
Question
What does this Java program print?
public class Main {
public static void main(String[] args) {
System.out.println(true ? 1 : 2.0);
}
}Options
- 1
- 1.0
- 2.0
- The program does not compile
Show the answer and the worked solution
Correct answer: B. 1.0
Worked solution
- The condition is true, so the value selected comes from the second operand, the int 1.
- The type of the whole conditional expression is settled at compile time by binary numeric promotion of int and double, which gives double.
- The selected 1 is therefore widened to 1.0 before printing, so the output is 1.0.
Answer: 1.0.
The idea
The branch not taken still influences the result, because the expression's type is decided before any branch is chosen. This is why mixing int and double in a conditional quietly changes what gets printed.
Shortcut. A ?: with an int and a double operand has type double, fixed at compile time, so the chosen 1 prints as 1.0.
Common trap. 1 looks only at the branch taken; the expression's type is promoted to double before any branch is chosen.
All Programming Fundamentals questions · placement mock tests