Skip to content

Beginner · Control flow and methods · topic 6 of 60 · 20 min

Decisions: if, else and the ternary

Explanation

if runs a block only when a boolean condition is true; else if and else handle the other cases, and only the first matching branch runs. Conditions must be real booleans in Java (if (count) does not compile). The ternary operator condition ? a : b picks one of two values in an expression.

Why decisions?

Programs must react to data: approve a loan only above a credit score, charge a late fee after the due date, show "out of stock" when quantity is zero. An if statement runs code only when its condition is true.

java
int marks = 72;
if (marks >= 90) {
    System.out.println("Grade A");
} else if (marks >= 60) {
    System.out.println("Grade B");
} else if (marks >= 35) {
    System.out.println("Grade C");
} else {
    System.out.println("Fail");
}
Prints Grade B. Java checks from the top and runs only the first branch whose condition is true.

Conditions must be boolean

Unlike C or JavaScript, Java does not treat numbers or objects as true/false. if (count) and if (name) do not compile. Write the comparison: if (count > 0), if (name != null). This removes a whole class of bugs.

java
int x = 3;
// if (x = 5) { }      // compile error: incompatible types: int cannot be converted to boolean
if (x == 5) { }        // correct comparison
Careful: With boolean variables the assignment bug still compiles: if (isPaid = true) assigns true and is always true. Write if (isPaid) instead of comparing with == true. Also, a semicolon right after the condition, if (x > 0); { … }, ends the if immediately and the block always runs.

Braces and the dangling else

Without braces, an if controls only the next single statement. An else always belongs to the nearest unmatched if, which can be different from what the indentation suggests. Always use braces, even for one line.

java
int a = 5, b = -1;
if (a > 0)
    if (b > 0)
        System.out.println("both positive");
else
    System.out.println("a is not positive");   // misleading! this else belongs to if (b > 0)
// Prints "a is not positive" even though a is 5.

Combining conditions

java
int age = 30, cibil = 760;
double salary = 55000;
if (age >= 21 && age <= 60 && cibil >= 750 && salary >= 25000) {
    System.out.println("Pre-approved for a personal loan");
}

The ternary operator

java
int items = 1;
String label = items == 1 ? "item" : "items";
System.out.println(items + " " + label);          // 1 item
int fee = amount >= 499 ? 0 : 40;
condition ? valueIfTrue : valueIfFalse is an expression: it produces a value.
Tip: Keep conditions readable: give long ones a name (boolean eligible = …;) and put the most common or most important case first. Avoid nesting ternaries; use if/else instead.
Think of it like this: An if/else-if chain is like the security check at an airport: you go through the first gate that applies to you (crew, business, economy) and you never pass through two gates.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Decisions: if, else and the ternary · 1/5

if / else

In this lesson your Java programs will start making decisions.

Prefer a video by a teacher? Find free videos on “java if else statement ternary operator tutorial” on YouTube ↗

In real life: Electricity slabs

A state electricity board bills in slabs. A billing module chooses the per-unit rate with an if/else-if chain. The rates below are sample values for practice, not a real tariff.

java
static double ratePerUnit(int units) {
    if (units <= 100) return 3.0;
    else if (units <= 300) return 5.0;
    else return 7.5;
}
ratePerUnit(80) → 3.0, ratePerUnit(250) → 5.0, ratePerUnit(420) → 7.5

Practice (0/3 done)

Task 1 · Question

What does this print? int t = 32; if (t > 35) System.out.println("Hot"); else if (t > 25) System.out.println("Warm"); else if (t > 30) System.out.println("Very warm"); else System.out.println("Cool");

Task 2 · Question

Which line has the bug? 1: int stock = 0; 2: if (stock == 0); { 3: System.out.println("Out of stock"); 4: }

Task 3 · Practice

Write a method static String grade(int marks) that returns "A" for 90+, "B" for 75–89, "C" for 60–74, "D" for 35–59 and "F" below 35, and "Invalid" for marks below 0 or above 100. Test it from main with at least 6 values including 0, 35, 100 and 101.

Quick quiz

Question 1

1.int n = 4; if (n) { … } What happens?

Question 2

2.How many branches of if / else if / else can run?

Question 3

3.What is x after: int x = 10 > 5 ? 1 : 2;

Question 4

4.boolean ok = false; if (ok = true) print("yes"); What happens?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

int n = 4; if (n) { … } What happens?

Answer: Compile error: int cannot be converted to boolean

Java conditions must be boolean.

How many branches of if / else if / else can run?

Answer: At most one

Only the first true branch runs.

What is x after: int x = 10 > 5 ? 1 : 2;

Answer: 1

The condition is true, so the first value is chosen.

boolean ok = false; if (ok = true) print("yes"); What happens?

Answer: Prints yes, because ok is assigned true

Assigning a boolean is a valid condition; this bug compiles. Write if (ok).

A switch case has code but no break. What happens?Related

Answer: Compile error: control cannot fall through

C# does not allow fall-through from a non-empty case (error CS0163).

From Decisions: if, else, switch and switch expressions

What happens without break at the end of a case?Related

Answer: Execution falls through to the next case

That is fall-through.

From Decisions: if, else and switch

Why does if (x = 0) never run its block?Related

Answer: Because it assigns 0 to x, and 0 counts as false

The assignment gives the value 0, which is false. You probably meant x == 0.

From Operators and decisions: if, else and switch

Which Kotlin feature replaces Java's switch statement?Related

Answer: when

when is Kotlin's flexible branching construct.

From Conditions: if and when

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Control flow and methods” before its exam: switch statements and switch expressions, Loops: for, while, do-while and for-each, Methods: parameters, return values and overloading, Reading errors and debugging.
  2. Module 2 exam: Control flow and methods · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Arrays and strings. 60 topics left in the course before the final exam.

← Previous: Type conversion and reading input