Command Palette

Search for a command to run...

Back to the lesson: Topic 2.2 — The Conditional (Ternary) Operator
Core Java · Example 3 of 3

Typing surprises: promotion, char, boxing

condition ? a : b is an expression that produces a when the condition is true and b otherwise. It's a compact if/else for choosing a value, with its own typing rules that can surprise you (numeric promotion and unboxing).

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given int hour = 14, print Good morning before 12 and Good afternoon otherwise, using one ternary inside println.

02

Print the absolute value of -9 and 5 with a ternary (no Math.abs).

03

Given int n = 0, print n is even or n is odd using a ternary inside the concatenation, then repeat for n = 7.

Explain it without notes

01

What's the difference between the conditional operator and an if statement?

02

Why does System.out.println(true ? 1 : 2.0); print 1.0?

03

How can a ternary throw a NullPointerException on a line with no method calls?

04

Why do you usually need brackets around a ternary inside a string concatenation?

Typing surprises: promotion, char, boxing
Sign in to run this example in your browser.

Expected output

1.0
b
98
1.0 is a Double
1 is an Integer