Introduction to Java · Introduction to Java Programming

Ternary Operator

Watch lectures

Ternary Operator

1. If-Else in One Line (beginner)

Ternary ? : is the only 3-part operator: condition ? valueIfTrue : valueIfFalse. Perfect for max, pass/fail, absolute value.

2. Basic Code (read as "if...then...else")

int marks = 75;
String result = (marks >= 40) ? "Pass" : "Fail"; // Pass
int max = (a > b) ? a : b;                        // bigger of a,b
int abs = (x < 0) ? -x : x;                       // absolute value
System.out.println(marks >= 40 ? "Pass" : "Fail");

Equivalent if (longer):

String result;
if (marks >= 40) result = "Pass";
else result = "Fail";

3. Nesting (exam favourite — add brackets!)

int m = 85;
String grade = (m >= 90) ? "A" : (m >= 75) ? "B" : (m >= 40) ? "C" : "F";
// m=85 → B (right-to-left grouping!)

Rule: both branches must give compatible types: (cond) ? 10 : "hi" is ERROR.

4. Traps

  • ? : returns a value — must assign or print it (not standalone like if).
  • Condition must be boolean: (x=5) ? ... fails.
  • Deep nesting unreadable — beyond 2 levels use if-else.

5. Exam Points

  • Rewrite if-else as ternary + predict nested output — 5 marks, very frequent.
  • Type-compatibility error — 2 marks, frequent.
Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.

← All Introduction to Java Programming modules