JOOPs Through Java
All lessons

Unit 2 · Java Fundamentals · 9 min

Decisions: if, else and switch

Control flow statements let your program choose different paths depending on a condition.

Why this matters

Real programs must react: pass or fail, valid or invalid, admin or student. Decisions are how that happens.

Real-life analogy

It is like a junction on your way to college: if the main road is blocked, take the side road, else go straight.

Syntax

Syntax
if (condition) {
    // runs when condition is true
} else if (anotherCondition) {
    // runs when the first was false and this is true
} else {
    // runs when nothing above was true
}

Example

Java
public class Result {
    public static void main(String[] args) {
        int marks = 72;

        if (marks >= 75) {
            System.out.println("Distinction");
        } else if (marks >= 60) {
            System.out.println("First Class");
        } else if (marks >= 35) {
            System.out.println("Pass");
        } else {
            System.out.println("Fail");
        }

        char grade = 'B';
        switch (grade) {
            case 'A': System.out.println("Excellent"); break;
            case 'B': System.out.println("Good"); break;
            default:  System.out.println("Keep practising");
        }
    }
}

Output

First Class
Good

Step by step

  1. 1Conditions are checked from top to bottom; the first true block runs and the rest are skipped.
  2. 2marks is 72, so the first check fails and the second (>= 60) succeeds.
  3. 3`switch` compares one value against several fixed cases.
  4. 4`break` stops the switch; without it execution falls through to the next case.
  5. 5`default` runs when no case matches.

Key points

  • Order of conditions matters in if-else-if chains
  • switch works with int, char, String and enum
  • Missing break causes fall-through, a favourite exam trick

Common mistakes

  • Writing `if (marks = 75)` instead of `==`
  • Putting a semicolon right after if(...) — the block then always runs
  • Forgetting break inside switch

Try it yourself

  • Check whether a number is positive, negative or zero.
  • Print the day name for a number 1–7 using switch.
Open the practice notebook