Java Switch Statement

In Java, the switch statement allows the execution of a single statement from multiple conditions. It shares similarities with the if-else-if ladder statement. The switch statement is compatible with data types such as byte, short, int, long, enum types, String, and certain wrapper types like Byte, Short, Int, and Long. Starting from Java 7, strings can also be used within the switch statement.

Important Points:

  • The switch expression in Java can have one or multiple case values.
  • Each case value must match the type of the switch expression and be a literal or constant value. It does not allow the use of variables.
  • Duplicate case values are not allowed and result in a compile-time error.
  • The Java switch expression supports byte, short, int, long (including their Wrapper types), enums, and strings.
  • Each case statement can be followed by an optional break statement. When encountered, the break statement causes control to exit the switch expression. Without a break statement, execution continues to the next case.
  • The switch expression can also include a default label, which is optional and serves as a fallback option when none of the case values match.

Syntax:

switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
  code to be executed if all cases are not matched;  
}

Flow Chart:

Example 1:

SwitchExample.java

public class SwitchExample {  
public static void main(String[] args) {  
    //Declaring a variable for switch expression  
    int number=20;  
    //Switch expression  
    switch(number){  
    //Case statements  
    case 100: System.out.println("100");  
    break;  
    case 200: System.out.println("200");  
    break;  
    case 300: System.out.println("300");  
    break;  
    //Default case statement  
    default:System.out.println("Not in 100, 200 or 300");  
    }  
}  
}

Output:

200

Example 2:

SwitchMonthExample.java

//Java Program to demonstrate the example of Switch statement  
//where we are printing month name for the given number  
public class SwitchMonthExample {    
public static void main(String[] args) {    
    //Specifying month number  
    int month=7;    
    String monthString="";  
    //Switch statement  
    switch(month){    
    //case statements within the switch block  
    case 1: monthString="1 - January";  
    break;    
    case 2: monthString="2 - February";  
    break;    
    case 3: monthString="3 - March";  
    break;    
    case 4: monthString="4 - April";  
    break;    
    case 5: monthString="5 - May";  
    break;    
    case 6: monthString="6 - June";  
    break;    
    case 7: monthString="7 - July";  
    break;    
    case 8: monthString="8 - August";  
    break;    
    case 9: monthString="9 - September";  
    break;    
    case 10: monthString="10 - October";  
    break;    
    case 11: monthString="11 - November";  
    break;    
    case 12: monthString="12 - December";  
    break;    
    default:System.out.println("Invalid Month!");    
    }    
    //Printing month of the given number  
    System.out.println(monthString);  
}    
}

Output:

7 - July

Switch Statement is a fall-through in Java:

In Java, the switch statement exhibits fall-through behavior. This means that if a break statement is not encountered, it will continue executing all statements following the first matching case.

Example:

SwitchExample2.java

//Java Switch Example where we are omitting the  
//break statement  
public class SwitchExample2 {  
public static void main(String[] args) {  
    int number=20;  
    //switch expression with int value  
    switch(number){  
    //switch cases without break statements  
    case 10: System.out.println("10");  
    case 20: System.out.println("20");  
    case 30: System.out.println("30");  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}

Output:

20
30
Not in 10, 20 or 30

Switch Statement with String in Java:

Starting from Java SE 7, the switch statement in Java allows the use of strings in switch expressions. However, it is important to note that the case statement must be a string literal.

Example:

SwitchStringExample.java

//Java Program to demonstrate the use of Java Switch  
//statement with String  
public class SwitchStringExample {    
public static void main(String[] args) {    
    //Declaring String variable  
    String levelString="Expert";  
    int level=0;  
    //Using String in Switch expression  
    switch(levelString){    
    //Using String Literal in Switch case  
    case "Beginner": level=1;  
    break;    
    case "Intermediate": level=2;  
    break;    
    case "Expert": level=3;  
    break;    
    default: level=0;  
    break;  
    }    
    System.out.println("Your Level is: "+level);  
}    
}

Output:

Your Level is: 3

Nested Switch Statement in Java:

In Java, it is possible to use switch statements within other switch statements, forming a nested switch statement. This allows for hierarchical and structured decision-making.

Example:

NestedSwitchExample.java

//Java Program to demonstrate the use of Java Nested Switch  
public class NestedSwitchExample {    
    public static void main(String args[])  
      {  
      //C - CSE, E - ECE, M - Mechanical  
        char branch = 'C';                 
        int collegeYear = 4;  
        switch( collegeYear )  
        {  
            case 1:  
                System.out.println("English, Maths, Science");  
                break;  
            case 2:  
                switch( branch )   
                {  
                    case 'C':  
                        System.out.println("Operating System, Java, Data Structure");  
                        break;  
                    case 'E':  
                        System.out.println("Micro processors, Logic switching theory");  
                        break;  
                    case 'M':  
                        System.out.println("Drawing, Manufacturing Machines");  
                        break;  
                }  
                break;  
            case 3:  
                switch( branch )   
                {  
                    case 'C':  
                        System.out.println("Computer Organization, MultiMedia");  
                        break;  
                    case 'E':  
                        System.out.println("Fundamentals of Logic Design, Microelectronics");  
                        break;  
                    case 'M':  
                        System.out.println("Internal Combustion Engines, Mechanical Vibration");  
                        break;  
                }  
                break;  
            case 4:  
                switch( branch )   
                {  
                    case 'C':  
                        System.out.println("Data Communication and Networks, MultiMedia");  
                        break;  
                    case 'E':  
                        System.out.println("Embedded System, Image Processing");  
                        break;  
                    case 'M':  
                        System.out.println("Production Technology, Thermal Engineering");  
                        break;  
                }  
                break;  
        }  
    }  
}

Output:

Data Communication and Networks, MultiMedia

Java Enum in Switch Statement:

In Java, the switch statement allows the utilization of enums. An enum in Java is a class that represents a fixed set of constants, which are immutable (similar to final variables). To define an enum, the keyword “enum” is used, followed by the constants enclosed in curly braces, separated by commas.

Example:

SwitchEnumExample.java

//Java Program to demonstrate the use of Enum  
//in switch statement  
public class SwitchEnumExample {      
       public enum Day {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
       public static void main(String args[])    
       {    
         Day[] DayNow = Day.values();    
           for (Day Now : DayNow)    
           {    
                switch (Now)    
                {    
                    case Sun:    
                        System.out.println("Sunday");    
                        break;    
                    case Mon:    
                        System.out.println("Monday");    
                        break;    
                    case Tue:    
                        System.out.println("Tuesday");    
                        break;         
                    case Wed:    
                        System.out.println("Wednesday");    
                        break;    
                    case Thu:    
                        System.out.println("Thursday");    
                        break;    
                    case Fri:    
                        System.out.println("Friday");    
                        break;    
                    case Sat:    
                        System.out.println("Saturday");    
                        break;    
                }    
            }    
        }    
}

Output:

Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

Java Wrapper in Switch Statement:

In Java, switch statements can make use of four wrapper classes: Byte, Short, Integer, and Long. These wrapper classes provide a way to handle primitive data types as objects. With these wrapper classes, switch statements can work with values of these types effectively.

Example:

WrapperInSwitchCaseExample.java

//Java Program to demonstrate the use of Wrapper class  
//in switch statement  
public class WrapperInSwitchCaseExample {       
       public static void main(String args[])  
       {         
            Integer age = 18;        
            switch (age)  
            {  
                case (16):            
                    System.out.println("You are under 18.");  
                    break;  
                case (18):                
                    System.out.println("You are eligible for vote.");  
                    break;  
                case (65):                
                    System.out.println("You are senior citizen.");  
                    break;  
                default:  
                    System.out.println("Please give the valid age.");  
                    break;  
            }             
        }  
}

Output:

You are eligible for vote.

We hope you have gained a thorough understanding of the Java Switch Statement. For further learning, please consider following tutorials.freshersnow.com.