AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardjavaternarytype promotion

~105s

The type of a conditional expression

What does this Java program print?

public class Main {
    public static void main(String[] args) {
        System.out.println(true ? 1 : 2.0);
    }
}
Show the answer and the worked solution

Correct answer: B.

1.0

Worked solution

  1. The condition is true, so the value selected comes from the second operand, the int 1.
  2. The type of the whole conditional expression is settled at compile time by binary numeric promotion of int and double, which gives double.
  3. 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.

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.

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
  2. 1.0
  3. 2.0
  4. The program does not compile
Show the answer and the worked solution

Correct answer: B. 1.0

Worked solution

  1. The condition is true, so the value selected comes from the second operand, the int 1.
  2. The type of the whole conditional expression is settled at compile time by binary numeric promotion of int and double, which gives double.
  3. 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