Java Switch Case Example – Learn switch case with Example

In this Java tutorial, we will understand the fundamental working of Java switch case statement. We will also understand 5 different Java switch-case example and their work. This Java switch case example tutorial includes- How to use Java switch-case with Java enum, String objects and with Multiple values. So, Let’s get started –

Java switch-case tutorial with Example


Java Switch-Case Example : Learn Selection Control

switch-case statements in Java are very similar to if-else-if… blocks. We can easily replace any if-else block with a switch-case block. The switch-case statement takes an Expression or Value and executes the matching cases (or blocks) that are satisfied with the same value.

Let’s first understand, the Java switch case syntax –

Syntax :

switch (theExpression) {
    case valueA:
        {
            // block-A; 
            // do your things -
            break;
        }
    case valueB:
        {
            // block-B;
            // do your things -
            break;
        }
    case valueC:
        {
            // block-C;
            // do your things -
            break;
            ...
            ...(n - times)
            ...
        }
    default:
        {
            // default-block;
            // do your things -
            break;
        }
}

 

In above syntax, the JVM will execute only that case whose value gets match with theExpression variable placed between the parenthesis of switch(…).


Points to Remember in Java switch-case :

In the above syntax, theExpression variable or object cannot hold any value of any data type. There are some limitations on holding values by the switch(…) statement. Java switch case works with Multiple values, but these values must be any one of these types –

  • byte,
  • short,
  • int,
  • char,
  • Byte (wrapper class),
  • Short (wrapper class),
  • Integer (wrapper class),
  • Character (wrapper class),
  • String values, and
  • enum.

Note*** : We can not use those expressions in Java switch-case statement that return us the values of some data type which are not specified in the above list. For example, If you use switch( someDoubleTypeValue ), you will face an Error : Cannot switch on a value of type Double. Only convertible int values, strings or enum variables are permitted.


Example 1 : Java switch-case String

In Java, the switch-case blocks run perfectly fine even when we provide a String literals/expression or Object instead of any Numeric value. We can provide String values to switch(…) or as an expression, and after its evaluation, one (or sometimes more) case would be executed.

Here are the example that would help you to better understand, How to use Java switch-case with String?

A Java Switch-Case example to handle Phone numbers as a String :

package com.shubhamklogic.switchcase;

/*    Java program - To provide information about the given Phone number.
        By ShubhamKLogic.com - A place that helps you, To grab the Logic behind the Code :)  */

public class SwitchClassExample1 {

    public static void main(String[] theArgs) {               // main method

        String phoneNo = "898989898";                                // The String

        System.out.println("*****************************************\n");

        switch (phoneNo.substring(0, 1)) {                           // Switch - The substring method would return String in switch(...)
                                                                                                  // Case - defined with
            case "6":                                                                      //  String Value - "6"
                System.out.println("The number " + phoneNo + " starts with : 6");
                break;

            case "7":
                System.out.println("The number " + phoneNo + " starts with : 7");
                break;

            case "8":                               
                System.out.println("The number " + phoneNo + " starts with : 8");
                break;

            case "9":
                System.out.println("The number " + phoneNo + " starts with : 9");
                break;

                    // If nothing got matched, the Default case would be executed.

            default:
                System.out.println("Can't tell anything about number!!!");
        }
        System.out.print("\n*****************************************");
    }
}

 

Output :

When you’ll run the above program, You will successfully get the following results –

*****************************************

The number 898989898 starts with : 8

*****************************************

Example 2 : Java switch-case String Array

A Java switch-case example program based on String Array –

package com.shubhamklogic.switchcase;

/*  Java program - To take input from user and execute the case by passing the String array value.
      By ShubhamKLogic.com - A place that helps you, To grab the Logic behind the Code :)  */

import java.util.Scanner;

public class SwitchCaseExample2 {                              // The Driver Class

    public static void main(String[] theArgs) {              // main() method

        String[] superCars = {                                                 // String array
            "Ferari",
            "Maserati",
            "Mercedes-Benz",
            "Land Rover",
            "BMW X7"
        };

        Scanner scan = new Scanner(System.in);

        System.out.println("**************************************\n");
        System.out.print("Enter your Lucky number : ");
        int num = scan.nextInt();                                                  // Taking Input from User
		
        if (num < superCars.length && num >= 0) {                  // Validating the Input
			
            switch (superCars[num]) {                                           // Switching to its matching case
				
                case "Ferari":
                    System.out.println("Congrats, You won Ferari!!!");
                    break;
                case "Maserati":
                    System.out.println("Congrats, You won Maserati!!!");
                    break;
                case "Mercedes-Benz":
                    System.out.println("Congrats, You won Mercedes-Benz!!!");
                    break;
                case "Land Rover":
                    System.out.println("Congrats, You won Land Rover!!!");
                    break;
                case "BMW X7":
                    System.out.println("Congrats, You won BMW X7!!!");
                    break;
                default:
                    System.out.println("Better Luck Next Time!!!");
                    break;
            }
        } else
                System.out.println("Better Luck Next Time!!!");		
        System.out.println("\n**************************************");
    }
}

 

Output :

When you will run the above Java switch-case example, You will successfully get the following Results –

************************************** 
Enter your Lucky number : 4 
Congrats, You won BMW X7 !!! 
**************************************

 


Example 3 – Java switch-case default: { }

In Java, it is not mandatory to have a default case in each switch-case statement. You can skip the default case in any switch-case statement.

However, The default case plays an important role, when none of the cases gets a match with the switch expression. In such cases, the code written in the default block gets executed.

Let’s take the above example WITHOUT the default case and see what happens –

package com.shubhamklogic.switchcase;

/*  Java program - To take input from user and Execute the case by passing the String array value, but It would not handle the default case.
      By ShubhamKLogic.com - A place that helps you, To grab the Logic behind the Code :)  */

import java.util.Scanner;

public class SwitchCaseExample3 {                                               // The Driver Class

    public static void main(String[] theArgs) {                               // main() method

        Scanner scan = new Scanner(System.in);

        System.out.println("**************************************\n");
        System.out.print("Enter your Lucky number : ");
        int usersNum = scan.nextInt();                                                 // Taking Input from User
		
        System.out.println("[INFO] : Executing the switch - case...");
			
        switch ( usersNum ) {                                                                  // Switching to its matching case
				
                case 1007 :
                    System.out.println("Congrats, You won Ferari!!!");
                    break;

                case 2007 :
                    System.out.println("Congrats, You won Maserati!!!");
                    break;

                case 3007:
                    System.out.println("Congrats, You won Mercedes!!!");
                    break;

                case 4007:
                    System.out.println("Congrats, You won Land Rover!!!");
                    break;

                case 5007:
                    System.out.println("Congrats, You won BMW X7!!!");
                    break;

                                     // Removed the default case { }

        }
        System.out.println("[INFO] : switch - case Ended...");
        
        System.out.println("\n**************************************");
    }
}

 

Output :

When you will run the above Java switch-case example, You will successfully get the following Results –

**************************************

Enter your Lucky number : 27
[INFO] : Executing the switch - case...
[INFO] : switch - case Ended...

**************************************

 

What’s the Logic : Behind the Code

As you can see in above example, the value 27, entered by the user that is kept in usersNum variable, didn’t satisfy any of the cases, so the program did not use that value, and came out of the switch case without doing anything. However, even we didn’t use the default-case, our program ran successfully.


Example 4 : Java switch-case Multiple values

It can be possible that a single case block gets executed for multiple values. To implement a Java switch-case Multiple values example, you need to remove the break; statement after the required cases, so that all the next cases can get executed until they reach to a break. –

package com.shubhamklogic.java.switchcase;

/* Java program - To take a number as user's favorite month, and, executes all the cases satisfying that month number.
     By ShubhamKLogic.com - A place that helps you, To grab the Logic behind the Code :) */

import java.util.Scanner;

class SwitchCaseExample4 {                                                             // The Driver class

    public static void main(String[] args) {                                        // main() method

        Scanner scan = new Scanner(System.in);

        System.out.println("*************************************************");
        System.out.print("Enter the number of your favorite month : ");

        short theMonth = scan.nextShort();                                                  // Taking a small number

        switch (theMonth) {                                                                              // Switching to that month case

            case 12:                                                                                                 // Removed the break;
            case 1:
                System.out.println("Hmm, It's Winter");                               // This block will execute in both the cases: 12 and 1
                break;

            case 2:
            case 3:
                System.out.println("Wow, It's Spring");
                break;

            case 4:
            case 5:
            case 6:
                System.out.println("Ohh, It's Summer");
                break;

            case 7:
            case 8:
            case 9:
                System.out.println("Hey, It's Monsoon");
                break;

            case 10:
            case 11:
                System.out.println("Great, It's Autumn");
                break;

            default:
                System.out.println("All seasons are Awesome.");
        }
        System.out.println("*************************************************");
    }
}

 

Output :

When you’ll run the above Java switch-case example, you’ll successfully get the following results :

*************************************************
Enter the number of your favorite month : 4
Ohh, It's Summer
*************************************************

 

What’s the Logic : Behind the Code

If you’ve noticed, then you already know that, when we ran the above program and user has submitted the value 4, the case 4, case 5 and case 6 got executed as there is no break statement after those cases.


Example 5 : Java switch-case Enum

Enum is a special data type in Java, using which we can declare and use a fixed set of variables. Let’s understand the Java switch-case with enum data type by converting the above program :

package com.shubhamklogic.java.switchcase;

class SwitchCaseExample5 {                                              // The Driver Class

    public enum TheSeason {                                                // An enum 
        WINTER,
        SPRING,
        SUMMER,
        MONSOON,
        AUTUMN
    };          // The enum

    public static void main(String[] args) {                        // main() method


        System.out.println("*************************************************");

        TheSeason myFavSeason = TheSeason.SPRING;       // Set the enum

        switch (myFavSeason) {                                                    // Passed enum in switch

            case WINTER:
                System.out.println("Hmm, It's Winter");
                break;

            case SPRING:
                System.out.println("Wow, It's Spring");
                break;

            case SUMMER:
                System.out.println("Ohh, It's Summer");
                break;

            case MONSOON:
                System.out.println("Hey, It's Monsoon");
                break;

            case AUTUMN:
                System.out.println("Yes, It's Autumn");
                break;

            default:
                System.out.println("All seasons are Awesome.");
        }
        System.out.println("*************************************************");
    }
}

 

Output :

When you’ll run the above Java program, you’ll successfully get the following results :

*************************************************
Wow, It's Spring
*************************************************

 


Wrap Up 

So far, we have learned How to use switch-case statement in Java. We also understood its workflow with 5 simple Java switch-case example using Java enum, String, Array and Multiple values. I have explained the logic behind the code in comments of above Java switch-case programs.

I hope, this article helped you to learn a bit more about- How to use switch-case in Java? If you have any doubt, query or suggestion, then do comment or send me a direct email via Google, I’ll try my best to give you the solution within a day.

Also, Rate this article on Facebook and, Don’t forget to check Other Useful Java Articles that you may like :

Read Next :

Leave a Comment