Branching: If-Else, Switch

if-else decides on any true/false condition, switch jumps to one matching case: BookBridge's menu picks its action here, and the missing break is the classic exam bug.

10 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The menu has to choose

BookBridge greets the librarian with:

1. Issue book 2. Return book 3. Exit

She types 2. Somewhere in your code, the program must take the returning-a-book path and ignore the other 2. Every useful program contains such forks: issue or deny, fine or no fine, valid or invalid.

Java gives you 2 branching tools: if-else, which tests any condition, and switch, which jumps straight to a matching case. Choosing the right one is half the marks.

Formula

The 2 syntaxes, exam form

if-else ladder:

if (condition) { ... }

else if (condition) { ... }

else { ... }

switch:

switch (expression) {

case value1: statements; break;

case value2: statements; break;

default: statements;

}

The condition in if must be a boolean. The switch expression may be byte, short, char, int, an enum or (since Java 7) a String, never boolean, long, float or double.

Practical

The BookBridge menu, choosing with switch

public class Menu {
    public static void main(String[] args) {
        int choice = 2;   // pretend the librarian typed 2
        switch (choice) {
            case 1:
                System.out.println("Issue book");
                break;
            case 2:
                System.out.println("Return book");
                break;
            case 3:
                System.out.println("Exit");
                break;
            default:
                System.out.println("Invalid choice");
        }
    }
}

Theory

What break is really doing

A switch does not test cases one by one like an if-else ladder. It jumps directly to the matching case label and starts executing from there, downward, until it meets a break or the switch ends.

That downward slide is called fall-through. With the breaks in place, choice 2 prints only "Return book". Delete them, and execution matched at case 2 keeps flowing into case 3 and default. Occasionally fall-through is used deliberately (grouping cases); usually it is a bug.

Quiz

int day = 2; switch (day) { case 1: System.out.print("A "); case 2: System.out.print("B "); case 3: System.out.print("C "); default: System.out.print("D"); } What prints?

  1. B
  2. B C D
  3. B C
  4. A B C D
Show the answer

B C D

No break anywhere, so after jumping to case 2 and printing B, execution falls through case 3 (C) and default (D). Option A assumes breaks that are not there. Option C forgets that default also lies on the fall-through path. Option D would need the match to start at case 1, but day is 2, so A is never printed. Predict-the-output switch questions are almost always testing exactly this.

Think first

Which tool for the fine?

BookBridge computes a fine message: 0 rupees prints "No fine", 1 to 50 prints "Small fine", above 50 prints "See librarian". Before tapping: switch or if-else, and why?

Show the answer

if-else ladder. The middle rule is a range (1 to 50), and case labels must be single constant values; you cannot write case 1..50 in this syllabus's Java. Ranges and compound conditions (fine > 50 && !cleared) are if-else territory. Use switch when ONE variable is compared against a handful of fixed discrete values, like the menu's 1, 2, 3.

Watch out

The 3 mark-eaters

Forgotten break: the number 1 switch bug; everything below the match executes.

Illegal switch types: switch on a boolean, long, float or double does not compile. If asked "can we switch on a boolean?", the answer is no, use if-else.

Non-constant case: case x: where x is a variable is a compile error; case labels must be compile-time constants.

Theory

Old friends, one upgrade

The syntax is deliberately the same as BCA104's C: your if-else and switch knowledge transfers line for line. Java adds 2 things worth remembering: if (x = 0) is a compile error rather than a silent bug (the condition must be boolean), and since Java 7 a switch can work on a String, so switch (command) with case "issue" and case "return" is legal Java, impossible in C. BookBridge's menu loop returns in the very next lesson.

Summary

Key takeaways

  • if-else tests boolean conditions and handles ranges and compound logic.
  • switch jumps to one matching case of a single expression: byte, short, char, int, enum or String (Java 7+), never boolean, long, float, double.
  • Without break, execution falls through every following case and default.
  • case labels must be compile-time constants; default catches everything unmatched.
  • Rule of thumb: discrete fixed values, switch; ranges or combined conditions, if-else.
  • Java refuses if (x = 0): conditions must be boolean, killing C's classic = vs == bug.
  • Memory hook: switch jumps in, break jumps out.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Introduction to Java

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Branching: If-Else, Switch · Java Programming Language · Gri-Learn