Switch Statement in Java with Examples

In this article, we will be taking a deep dive into switch statements in Java. Switch statements are very similar to If-Else statements. As we proceed through the article, we will understand the switch case with the help of a flowchart, its syntax, and a couple of programs with outputs.

We will also examine some key points to keep in mind when using switch statements, as well as try a few variations of the switch statements. I recommend that you practice the codes shown in the article and try experimenting with variations of the same codes to master the concept.

What is the use of switch statements in Java?

Switch statements are very similar to If-Elseif-Else statements, as both of them are multi-way branch statements that execute one statement from multiple conditions.

Programmers prefer to switch statements over If-Else statements as it helps you avoid writing multiple If-Else statements. Switch statements offer a simple method to direct execution to different sections of code depending on the value of the expression.

The expression of the Java switch statements can either be a byte, char, int, or short primitive data type. However, with the oncoming of JDK7, switch statements also work with the Strings, Wrapper classes, and enums.

What is the syntax of Java switch-case statements?

Before we proceed further, let us take a look at the syntax of the switch statements,

switch(expression)
{    
case value1:    
<statements1>    
 		break; 
case value2:    
 		<statements2>    
break; 
default:     
   		<statements3>
}   

Let us take a moment to understand the syntax shown above. In the first statement, the expression holds the parameter that we are going to compare. When the expression matches “value1”, the set of “statements1” gets executed. If the expression matches “value2”, the set of “statements1” gets executed, and so on.

Then what is the default statement? Well, if none of the values match the given expression, the set of statements under the default case gets executed. Before we proceed from this topic, let us perfect the syntax of the switch statements by taking a look at a flowchart.

java switch statement

Key points to remember while using switch statements

Before we proceed to look at some examples and variations of the Java switch statements, let us take a look at some points to keep in mind while programming using switch statements.

1. Irrespective of the number of cases that check if the value matches the expression, duplicate values are not allowed in switch statements.

2. It is crucial that the value given for a case be the same as the datatype you passed in the switch

3. When you pass values in case, you must be careful to always give only constant values and not variables.

4. The break statement present at the end of each case terminates the statement sequence

5. It is optional to put the break statement at the end of a case statement; however, with the absence of the break statement, the program will continue execution of the next case also.

6. Even the default statement is optional, and you can write it anywhere within the switch statement.

7. If the default statement is not at the end of the switch case, you must remember to put a break statement at the end of the default case.

Examples and variations of switch statements in Java

Now that we have the basics sorted, let us take a look at a couple of codes and try experimenting with the syntax a little bit.

1. Regular switch case

public class Main
{
 
    public static void main(String[] args)
    {
        int number = 7;
        String FirstCode;
 
        switch (number) 
        {
            case 1:
                FirstCode = "One";
                break;
 
            case 2:
                FirstCode = "Two";
                break;
 
            case 3:
                FirstCode = "Three";
                break;
 
            case 4:
                FirstCode = "Four";
                break;
 
            case 5:
                FirstCode = "Five";
                break;
 
            default:
                FirstCode = "FirstCode";
        }
        System.out.println(FirstCode);
    }
}

Output:

FirstCode

In the above program, since the value of the variable “number” was 7, it did not match any of the cases. Hence, it opted for the default case and printed “FirstCode”.

2. Nested switch statement

Similar to If-Else statements, switch case statements can also be nested.

Here is an example:

public class Main
{
 
    public static void main(String[] args)
    {
        int number = 1;
        String FirstCode;
        String x = "FirstCode";
        String s = "";

 
        switch (number) 
        {
            case 1:
                FirstCode = "One";
                
                switch (x) 
                {
                    case "FirstCode":
                        s = "FirstCode";
                        break;
                        
                    default:
                        s = "The String is Not FirstCode";
                }
                break;
                
            case 2:
                FirstCode = "Two";
                break;
 
            case 3:
                FirstCode = "Three";
                break;
 
            case 4:
                FirstCode = "Four";
                break;
 
            case 5:
                FirstCode = "Five";
                break;
 
            default:
                FirstCode = "FirstCode";
        }
        System.out.println(FirstCode);
        System.out.println(s);

    }
}

Output:

One
FirstCode

In the program shown above, since the number has been matched to 1, it first prints “One” and then enters the nested switch case, where it compares the string x. Since it matches the case” FirstCode”, it prints the same.

3. Removing the break statement

public class Main
{
 
    public static void main(String[] args)
    {
        int number = 1;
        String FirstCode;
 
        switch (number) 
        {
            case 1:
                FirstCode = "One";
                
            case 2:
                FirstCode = "Two";
 
            case 3:
                FirstCode = "Three";
                break;
 
            case 4:
                FirstCode = "Four";
                break;
 
            case 5:
                FirstCode = "Five";
                break;
 
            default:
                FirstCode = "FirstCode";
        }
        System.out.println(FirstCode);

    }
}

Output:

Three

In this example, we have removed the break statements from cases 1 and 2; this means that even though the variable “number” matches case 1, due to the absence of the break statement, it will keep executing case 3, where it finally hits the break statement. Hence, the variable “First Code” gets updated to Three and thus prints the same.

4. Placing the default statement in a different location

As mentioned above, the default statement need not always be at the bottom of the switch statements, it can literally be anywhere within the switch statements. Here is an example where the break statement is present at the top of the switch statements.

public class Main
{
 
    public static void main(String[] args)
    {
        int number = 10;
        String FirstCode;
 
        switch (number) 
        {
            default:
                FirstCode = "FirstCode";
                break;

            case 1:
                FirstCode = "One";
                break;
                
            case 2:
                FirstCode = "Two";
                break;
 
            case 3:
                FirstCode = "Three";
                break;
 
            case 4:
                FirstCode = "Four";
                break;
 
            case 5:
                FirstCode = "Five";
                break;
 
            
        }
        System.out.println(FirstCode);
    }
}

Output:

FirstCode

5. Playing with the case variables

A good feature of the switch statements is that we can write the case even in terms of a constant expression.

Here is an example:

public class Main
{
 
    public static void main(String[] args)
    {
        int number = 3;
        String FirstCode;
 
        switch (number) 
        {
            default:
                FirstCode = "FirstCode";
                break;

            case (9 - 8): //case 1
                FirstCode = "One";
                break;
                
            case 2: //case 2
                FirstCode = "Two";
                break;
 
            case (30 - 27)://case 3
                FirstCode = "Three";
                break;
 
            case (8 - 4): //case 4
                FirstCode = "Four";
                break;
 
            case (2 + 3): //case 5
                FirstCode = "Five";
                break;
 
            
        }
        System.out.println(FirstCode);

    }
}

Output

Three

6. Using Enum in switch statements.

As mentioned earlier, since Java Development Kit 7, Switch cases can be used along with Wrapper class, strings, and also enums.

Here is an example showcasing the use of enums in switch statements:

public class FirstCode 
{
    public enum Num { one, two, three, four, five }
    public static void main(String args[])
    {
 
        Num[] NumNow = Num.values();
 
        for (Num Now : NumNow) {
 
            switch (Now) {
 
            case one:
                System.out.println("1");
 
                break;
 
             case two:
                System.out.println("2");
                break;
 
            case three:
                System.out.println("3");
                break;
 
            case four:
                System.out.println("4");
                break;
 
            case five:
                System.out.println("5");
                break;
 
            }
        }
    }
}

Output:

1
2
3
4
5

7. Using Wrapper class in a switch statement

We have already seen that Java enables us to use wrapper classes in switch statements. But wait! What are wrapper classes? Wrapper classes enable us to transform primitive data types into objects. We can use Byte, Integer, Short, and Long variables with wrapper classes in switch statements in Java.

Here is an example:

public class FirstCode
{     
    public static void main(String args[])
    {     
        Integer age = 18;     
        switch (age)
        {
          case (16):        
            System.out.println("Ineligible to vote!");
            break;
          case (18):          
            System.out.println("Eligible to vote!");
            break;
          case (65):          
            System.out.println("Senior Citizen");
            break;
          default:
            System.out.println("Please enter a valid age.");
        }        
    }
}

Output

Eligible to vote!

In the above code, the variable “age” is a wrapper class of datatype “Integer.”

Conclusion

You have now seen how switch statements are used in Java programming language. You have now learned the use of switch statements, their syntax, a flowchart representing switch case statements, and a couple of key points to remember while using them.

We have also seen programs of regular switch cases and nested switch cases. We also tried some variations, like omitting the break statements, changing the location of the default statements, using enums, and more.

Leave a Reply

Your email address will not be published. Required fields are marked *