SyntaxPilot
Courses/Java/Lesson 5

Java · Lesson 5 of 51 · 13 min

if / else and switch

queued

These are the notes for Java episode 5. Up to now every program ran every line, top to bottom. Today the program learns to decide: if and else, the three traps that catch every beginner, else if ladders (and why their order matters), nested if, && and the ternary operator ?:, and then switch: case, break, default, fall-through, arrow cases, switch on a String, and switch expressions. Every example below runs as-is in the SyntaxPilot compiler, and every output and error message is the real one from javac 21.

The problem: a ticket counter that can't decide

A cinema has two prices: kids under 12 pay ₹100, adults pay ₹200. The clerk looks at you and decides. Our programs can't: they run every line, every time. The obvious attempt prints both prices:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int age = sc.nextInt();
        System.out.println("Child ticket: Rs 100");
        System.out.println("Adult ticket: Rs 200");
    }
}

Input 8:

Child ticket: Rs 100
Adult ticket: Rs 200

Why it failed: Java runs every statement in order. We have no way to say "run this line only sometimes". We need a way to skip.

if and else

Real-life example: a guard at the kids' gate asks exactly one yes/no question: "Are you under 12?" Yes, you go through the kids' gate. No, you go to the adults' gate.

At the cinema In Java
The guard's yes/no question the condition: age < 12
"Yes": go through the kids' gate the if block { ... } runs
"No": the other gate the else block runs
  • A condition is an expression that gives a boolean: true or false. Comparisons from episode 3 (<, <=, >, >=, ==, !=) all give booleans.
  • A block is a group of statements inside curly brackets { }.
  • if (condition) { ... } runs the block only when the condition is true.
  • else { ... } runs only when it is false. Exactly one of the two blocks runs, never both.
public class Main {
    public static void main(String[] args) {
        int age = 8;
        if (age < 12) {
            System.out.println("Child ticket: Rs 100");
        }
        System.out.println("Enjoy the movie!");
    }
}
Child ticket: Rs 100
Enjoy the movie!

With int age = 30; the block is skipped:

Enjoy the movie!

Add else for the adult:

public class Main {
    public static void main(String[] args) {
        int age = 30;
        if (age < 12) {
            System.out.println("Child ticket: Rs 100");
        } else {
            System.out.println("Adult ticket: Rs 200");
        }
    }
}
Adult ticket: Rs 200

How if / else flows

            age < 12 ?
           /          \
        true          false
         |              |
  "Child: Rs 100"  "Adult: Rs 200"
           \          /
         the next statement

Three if traps

Trap 1: = instead of ==

int age = 30;
if (age = 12) {
    System.out.println("Twelve");
}
Main.java:4: error: incompatible types: int cannot be converted to boolean
        if (age = 12) {
                ^
1 error

age = 12 puts 12 into age and its value is the int 12. An if needs a boolean. Use == to ask: if (age == 12).

Trap 2: a semicolon after the condition

int age = 30;
if (age < 12); {
    System.out.println("Child ticket: Rs 100");
}
Child ticket: Rs 100

No error, wrong answer. The ; is an empty statement and becomes the whole body of the if. The block below is just an ordinary block that always runs.

Trap 3: no curly brackets

int age = 30;
if (age < 12)
    System.out.println("Child ticket: Rs 100");
    System.out.println("Free popcorn for kids!");
Free popcorn for kids!

Without { } the if controls only the next statement. Indentation is for humans; Java ignores it. Always write the curly brackets.

else-if ladders

Grades: 90+ is A, 75+ is B, 50+ is C, below 50 is F. Four paths. The obvious attempt is four separate ifs:

int marks = 95;
if (marks >= 90) System.out.println("Grade A");
if (marks >= 75) System.out.println("Grade B");
if (marks >= 50) System.out.println("Grade C");
if (marks < 50) System.out.println("Grade F");
Grade A
Grade B
Grade C

Separate ifs don't know about each other: 95 passes three of the questions. Chain them into an else-if ladder: Java asks in order and the first true condition wins; the rest are skipped.

public class Main {
    public static void main(String[] args) {
        int marks = 95;
        if (marks >= 90) {
            System.out.println("Grade A");
        } else if (marks >= 75) {
            System.out.println("Grade B");
        } else if (marks >= 50) {
            System.out.println("Grade C");
        } else {
            System.out.println("Grade F");
        }
    }
}
Grade A

Order matters

int marks = 95;
if (marks >= 50) {
    System.out.println("Grade C");
} else if (marks >= 75) {
    System.out.println("Grade B");
} else if (marks >= 90) {
    System.out.println("Grade A");
}
Grade C

marks >= 50 was true first, so the ladder stopped. Put the strictest condition at the top.

Nested if, && and the ternary operator

A student discount needs two checks: under 25, and then a college ID. An if inside another if's block is a nested if:

public class Main {
    public static void main(String[] args) {
        int age = 20;
        boolean hasId = true;
        if (age < 25) {
            if (hasId) {
                System.out.println("Student discount: 20% off");
            } else {
                System.out.println("Show your college ID");
            }
        } else {
            System.out.println("Regular price");
        }
    }
}
Student discount: 20% off

If you only care that both are true, combine them with && (episode 3):

int age = 20;
boolean hasId = false;
if (age < 25 && hasId) {
    System.out.println("Student discount: 20% off");
} else {
    System.out.println("Regular price");
}
Regular price

The ternary operator ?:

When a decision only picks one of two values, write condition ? valueIfTrue : valueIfFalse. It's called ternary because it has three parts.

int age = 30;
String ticket = (age < 12) ? "Child" : "Adult";
System.out.println(ticket + " ticket");
Adult ticket

Use it for small choices. For anything with statements or several branches, a normal if/else is clearer.

switch, case, break and default

An office canteen has a different lunch for each day 1 to 7. An else-if ladder would ask day == 1, day == 2, ... seven times about the same variable. Real-life example: a lift. You don't stop at each floor asking "is this 3?"; you press 3 and go straight there. switch takes one value and jumps to the matching case.

public class Main {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday: Rajma chawal");
            case 2:
                System.out.println("Tuesday: Chole bhature");
            case 3:
                System.out.println("Wednesday: Paneer");
            case 4:
                System.out.println("Thursday: Kadhi");
            default:
                System.out.println("Weekend: Biryani");
        }
    }
}
Wednesday: Paneer
Thursday: Kadhi
Weekend: Biryani

This is fall-through: a case label is only an entry point. Once Java enters at case 3, it keeps running every statement below, through the other cases, until something stops it. That something is break, which leaves the switch immediately.

public class Main {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1:
                System.out.println("Monday: Rajma chawal");
                break;
            case 2:
                System.out.println("Tuesday: Chole bhature");
                break;
            case 3:
                System.out.println("Wednesday: Paneer");
                break;
            default:
                System.out.println("Weekend: Biryani");
        }
    }
}
Wednesday: Paneer
  • default is the else of a switch: it runs when no case matches (try day = 9).
  • Fall-through is occasionally useful on purpose (several cases sharing code), but in old-style switches every case normally ends with break.
  • Two cases with the same value give error: duplicate case label.

Modern switch: arrow cases (Java 14+)

Write -> instead of : and that case never falls through, so no break is needed. switch also works on String, char, int (and byte, short, enums):

public class Main {
    public static void main(String[] args) {
        String coach = "S4";
        switch (coach) {
            case "A1" -> System.out.println("AC 2-tier");
            case "B2" -> System.out.println("AC 3-tier");
            case "S4" -> System.out.println("Sleeper");
            default -> System.out.println("General");
        }
    }
}
Sleeper

switch does not work on double: switch (price) with a double gives error: selector type double is not allowed. Decimals are rarely exactly equal, so use an if ladder with ranges.

Switch expressions

A switch can give back a value, like the ternary. Several values can share a case with commas. Note the ; after the closing }: the whole switch is one assignment.

int day = 7;
String type = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
};
System.out.println(type);
Main.java:4: error: the switch expression does not cover all possible input values
        String type = switch (day) {
                      ^
1 error

day is an int: it could be 9 or -5. A switch expression must produce a value for every possible input (it must be exhaustive), so add default:

public class Main {
    public static void main(String[] args) {
        int day = 7;
        String type = switch (day) {
            case 1, 2, 3, 4, 5 -> "Weekday";
            case 6, 7 -> "Weekend";
            default -> "Not a day";
        };
        System.out.println(type);
    }
}
Weekend

if or switch?

Use When
if / else if ranges (marks >= 90), several different variables, boolean checks, double values
switch one variable compared with fixed values (1, 2, 3 or "A1", "B2")
switch expression the same, when you want a value back
ternary ?: a tiny either/or value

Common mistakes (and the real error messages)

Mistake Real message Why Fix
if (age = 12) incompatible types: int cannot be converted to boolean = assigns, it doesn't compare if (age == 12)
if (age < 12); { ... } no error, the block always runs the ; is the if's body no ; after the condition
if without { } and two indented lines no error, the second line always runs only one statement belongs to the if always use { }
separate ifs for grades no error, several grades print each if is independent else if ladder
ladder with >= 50 first no error, 95 gets a C first true wins strictest condition first
case 3: without break no error, the next cases run too fall-through break; or arrow cases
String t = switch (day) { case 6, 7 -> ... }; the switch expression does not cover all possible input values no value for other inputs default -> ...
switch on a double selector type double is not allowed doubles aren't switchable if ladder with ranges
two case 1: labels duplicate case label each value can appear once remove or merge
a variable set only in some branches variable bill might not have been initialized some path leaves it unset add an else, or initialise it

Mini project: electricity bill with slabs

Rates: first 100 units ₹3 each, units 101-200 ₹5 each, above 200 ₹8 each. Bad readings (negative) are rejected first.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Units used:");
        int units = sc.nextInt();
        if (units < 0) {
            System.out.println("Invalid reading");
        } else if (units <= 100) {
            System.out.println("Bill: Rs " + units * 3);
        } else if (units <= 200) {
            System.out.println("Bill: Rs " + (300 + (units - 100) * 5));
        } else {
            System.out.println("Bill: Rs " + (800 + (units - 200) * 8));
        }
    }
}

Input 250:

Units used:
Bill: Rs 1200

(100 × 3 = 300, plus 100 × 5 = 500, plus 50 × 8 = 400.) Input -5:

Units used:
Invalid reading

Extend it: store the bill in a variable first. If you set it only in the if and else if branches (no final else), then print it, Java refuses:

public class Main {
    public static void main(String[] args) {
        int units = 250;
        double bill;
        if (units <= 100) {
            bill = units * 3;
        } else if (units <= 200) {
            bill = 300 + (units - 100) * 5;
        }
        System.out.println(bill);
    }
}
Main.java:10: error: variable bill might not have been initialized
        System.out.println(bill);
                           ^
1 error

Java checks every path. Give every path a value (add else) and it compiles. Then add a 10% surcharge with a second if (units > 300).

Practice

  1. Read a number and print even or odd.
  2. Read three numbers and print the largest.
  3. Read marks (0-100) and print the grade with an else-if ladder; print Invalid for anything outside 0-100.
  4. Read a month number 1-12 and print its number of days with a switch expression (ignore leap years).
  5. Read a year and print whether it is a leap year.
Solutions and hints
  1. System.out.println(n % 2 == 0 ? "even" : "odd");
  2. java int max = a; if (b > max) { max = b; } if (c > max) { max = c; } System.out.println(max);
  3. Put the invalid check first: if (marks < 0 || marks > 100) { ... } else if (marks >= 90) { ... } ...
  4. java int days = switch (month) { case 2 -> 28; case 4, 6, 9, 11 -> 30; case 1, 3, 5, 7, 8, 10, 12 -> 31; default -> -1; };
  5. A year is a leap year if it is divisible by 400, or divisible by 4 but not by 100: (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0).

Quick quiz

What does this print?

int x = 2;
switch (x) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C");
            break;
    default: System.out.print("D");
}
  • A. B
  • B. BC
  • C. BCD
  • D. ABCD
Answer

B. BC. Java enters at case 2 and prints B. There's no break, so it falls into case 3, prints C, and the break there leaves the switch. D never runs.

Interview questions

  1. What is fall-through in a switch? Execution continues from the matching case into the following cases until a break (or the end). Arrow cases (->) never fall through.
  2. Can you switch on a String? On a double? On a String, yes (since Java 7, compared with equals). On a double, float, long or boolean, no.
  3. What is the difference between a switch statement and a switch expression? A statement just runs code; an expression produces a value, uses -> (or yield), and must be exhaustive.
  4. Why does if (x = 5) not compile in Java but compiles in C? In Java the condition must be a boolean; x = 5 is an int. C treats any non-zero number as true.
  5. When would you choose if-else over switch? Ranges, several variables, boolean logic, or floating-point values.
  6. What does the ternary operator return? One of its two value operands, chosen by the condition; both branches must give compatible types.

Glossary

Term Meaning Example
condition an expression that is true or false, used to decide age < 12
boolean the type with only two values, true and false boolean hasId = true;
block statements grouped by curly brackets { System.out.println("Hi"); }
if statement runs its block only when the condition is true if (age < 12) { ... }
else the block that runs when the if condition is false } else { ... }
else-if ladder a chain of conditions; the first true one wins if ... else if ... else
nested if an if inside another if's block discount check
empty statement a lone ; that does nothing if (x);
ternary operator cond ? a : b, picks one of two values (age < 12) ? "Child" : "Adult"
switch jumps to the case matching one value switch (day) { ... }
case one value a switch can match case 3:
break leaves the switch (or a loop) immediately break;
default runs when no case matches default -> "General";
fall-through running on into the next cases after a match missing break
arrow case case X -> ..., never falls through case "S4" -> ...
switch expression a switch that gives back a value String t = switch (d) { ... };
exhaustive covers every possible input value a switch expression with default

Summary

  • if (condition) { } runs a block only when the condition is true; else { } is the other path.
  • == asks, = puts. No ; after the condition. Always use { }.
  • In an else-if ladder the first true condition wins, so put the strictest first.
  • Nested ifs and && combine checks; cond ? a : b picks a value.
  • switch jumps to the matching case; without break it falls through; default catches the rest.
  • Arrow cases never fall through; a switch expression returns a value and must be exhaustive.

Next episode: loops, for, while and do-while, so the program can repeat work instead of copying code.