08 Java Fundamentals | Switch statements in Java | By Dummy for Dummies

 

INTRODUCTION:

 Switch  is another way to handle more than one pathways a code can take. When the conditions are more than just few then it is prefered to use  Switches . There are few differences based on which programmer can decide when to use  if-else   or  Switch statements


KEY FEATURES OF SWITCHES

⦿ Unlike  if-else   Switch  does not perform operations for conditions

⦿  Switch  is applied on one single variable

⦿ All possible values that variable may contain are listed as cases 

⦿ Each case must contain value NOT variable

⦿ A default case is added at the ended, executes if none matches


Demonstration:

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");

        }

    }

}

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

⦿ Unlike  if else , here if you do not use  break  then all of the cases will execute after the one that matches
⦿ To execute a single match you must use  break  statement. Here is a demonstration

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");

        }

    }

}


OUTPUT:
The value in variable is 2 The value in variable is 3 None of the cases match 


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

GROUPED CASES

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

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!");

        }

    }

}


OUTPUT (for 1,2,3,4,5)
It's a weekday 

OUTPUT (for 6,7)
It's a weekend 

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

⦿ Must use  break  statement.

⦿  Switch  does NOT work on  long  float  double  or  boolean  datatypes

⦿  Switch  works on  byte  short  int  char  and  String .

⦿ Use  if-else  when conditions involve ranges or complex logic.

⦿ Use  Switch  when one variable is compared against many fixed values.

⦿ The value must be written in their actual representation in front of case e.g.
          case "monday"   For Strings 
          case "@"        For Characters 
          case 12        For integers  

⦿ Datatype of the variable on which switch is made and the values in cases MUST match or the program will throw error

⦿ In  if-else  each  if  if else  and  else  has their own set of curly brackets  { } . In case of  switch  a single set of curly brackets  { }  enclose all cases along with default



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.

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(); // Convert to lowercase for consistency


        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();

    }

}


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:

1. Check Balance

2. Deposit Money

3. Withdraw Money

4. Exit

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:
⦿ Scanner for input
⦿ A switch statement with multiple cases
⦿ A variable to keep track of balance
⦿ At least one printf statement for formatted output


EXAMPLE 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.