← Back to all posts

08 Java Fundamentals

Switch Statementsin Java

By Dummy for Dummies


Introduction

Switch is another way to handle a program that can go down more than one path. When you're checking a single variable against a handful of fixed values, Switch is usually the cleaner choice over a long if-else chain. We'll get into exactly when to reach for each one.


Key Features of Switches


Demonstration

Java
public class Main {
    public static void main(String[] args) {
        int n = 2;  // Variable to test

        switch (n) {  // Applying switch on n variable
            case 1:   // Case for value 1
                System.out.println("The value in variable is 1");
                break;
            case 2:   // Case for value 2
                System.out.println("The value in variable is 2");
                break;
            case 3:   // Case for value 3
                System.out.println("The value in variable is 3");
                break;
            default:   // Default case for any other value
                System.out.println("None of the cases matches");
        }
    }
}
Console Output
The value in variable is 2

Here n contains 2, it will match the second case and execute the print code inside it.


Code Without Break Statement

Java
public class Main {
    public static void main(String[] args) {
        int n = 2;  // Variable to test

        switch (n) {
            case 1:
                System.out.println("The value in variable is 1");
            case 2:
                System.out.println("The value in variable is 2");
            case 3:
                System.out.println("The value in variable is 3");
            default:
                System.out.println("None of the cases match");
        }
    }
}
Console Output
The value in variable is 2 The value in variable is 3 None of the cases match

Without break, there is no stopping them. Execution of one triggers execution of all remaining statements. Therefore using break becomes extremely necessary.


Grouped Cases

Sometimes we want multiple cases to run the same code. One way is to put the same code inside all those cases. But a cleaner method is below:

Java
public class Main {
    public static void main(String[] args) {
        int day = 5;  // 1 = Monday, 7 = Sunday

        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("It's a weekday");
                break;
            case 6:
            case 7:
                System.out.println("It's a weekend");
                break;
            default:
                System.out.println("It's not a day!");
        }
    }
}
Console Output (for 1 to 5)
It's a weekday
Console Output (for 6 to 7)
It's a weekend
Console Output (for any other number)
It's not a day!

Note: The default case is not compulsory. If no case matches and there's no default, the program will just do nothing.


Points to Remember


Exercise

Let's do an exercise for what we studied in this post. Study this code, break it down, analyze it and identify the concepts used here. It would be even better if you write down your observations and make a mini report on it.

Java
import java.util.Scanner;

public class SwitchExercise {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("  SWITCH STATEMENT EXERCISE  ");
        System.out.print("Enter a day number (1-7): ");
        int day = input.nextInt();

        // Simple switch with grouped cases
        switch (day) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("It's a weekday. Time to study and work!");
                break;
            case 6:
            case 7:
                System.out.println("It's the weekend. Enjoy your rest!");
                break;
            default:
                System.out.println("Invalid day number! Please enter 1 to 7.");
        }

        // Switch on characters
        System.out.print("Enter a grade (A, B, C, D, F): ");
        char grade = input.next().charAt(0);

        switch (grade) {
            case 'A':
                System.out.println("Excellent!");
                break;
            case 'B':
                System.out.println("Good job");
                break;
            case 'C':
                System.out.println("Fair, but can improve");
                break;
            case 'D':
                System.out.println("Needs improvement");
                break;
            case 'F':
                System.out.println("Failed");
                break;
            default:
                System.out.println("Invalid grade input!");
        }

        // Switch on strings
        System.out.print("Enter your favorite fruit: ");
        String fruit = input.next().toLowerCase();

        switch (fruit) {
            case "apple":
            case "banana":
            case "orange":
                System.out.println("That's a healthy choice!");
                break;
            case "burger":
            case "pizza":
                System.out.println("That's tasty but not healthy!");
                break;
            default:
                System.out.println("Interesting choice!");
        }

        input.close();
    }
}
Console Output
SWITCH STATEMENT EXERCISE Enter a day number (1-7): 3 It's a weekday. Time to study and work! Enter a grade (A, B, C, D, F): B Good job Enter your favorite fruit: apple That's a healthy choice!

Mini Project: Simple Banking System

Your project is to create a simple Java program that works like a small banking system using a menu. The program should display the following menu to the user:

The user should enter a choice, and the program should use a switch statement to handle that choice. If the user selects Deposit Money or Withdraw Money, the program should update the balance variable accordingly.

If the user enters an invalid choice, the program should display "Invalid Option."

Finally, the program should continue until the user chooses Exit.

While writing the program, make sure you use:


Example Output

Console Output
SIMPLE BANKING SYSTEM Your current balance is: $1000.00 Menu: 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 2 Enter amount to deposit: 500 Deposit successful! New balance: $1500.00 Menu: 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 3 Enter amount to withdraw: 200 Withdrawal successful! Remaining balance: $1300.00 Menu: 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 1 Your current balance is: $1300.00 Menu: 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 5 Invalid Option. Menu: 1. Check Balance 2. Deposit Money 3. Withdraw Money 4. Exit Enter your choice: 4 Thank you for using our banking system. Goodbye!

Closing

That's it for switch statements in Java. They're super useful when one variable has many possible fixed values. Once you know when to use if-else and when to use switch, your programs become cleaner and easier to read.

← Previous 07 - If-else statements in Java Next → 09 - While Loop in Java