August 7, 2022

Java switch case Statement With Examples

Switch statement is Java's selection statement which can have a number of possible execution paths. Another selection statement if-else-if ladder in Java also executes one of the code block based on the evaluation of the condition, switch-case in Java provides an easier and more readable alternative to do the same rather than using a large if-else-if ladder.

Syntax of the Java switch-case statement is-

switch(expression) {
 case value1:
  // statements
  break;
 case value2:
  // statements
  break;
 .
 .
 .
 case valueN :
  // statements
  break;
 default:
  // statements
}

The body of a switch statement is known as a switch block. A switch block contains one or more case labels and an optional default label.

How does Java switch statement work

The switch statement evaluates its expression and compare it with the value of each case label and executes all statements following the matching case label.

If switch statement expression doesn't match any of the case label then the statements following the default label are executed. Note that having a default section is not mandatory. If default section is not there and none of the case label matches the expression then control comes out of the switch block with out executing any statement.

Having the break statement with in the switch block is very important as it terminates the switch statement. As soon as the break statement is encountered control comes out of the switch statement. The break statements are necessary because without them all statements in the subsequent case labels after the matching case label are executed in sequence even if the value of the case labels don't match the switch statement expression.

Type of switch statement expression

Switch statement works with one of the following types-

  1. Primitive data types- byte, short, char, and int
  2. Enumerated types
  3. Wrapper classes that wrap certain primitive types: Character, Byte, Short, and Integer
  4. String (Java 7 onward)

Some important points about switch-case in Java are as follows-

  • Switch statement is used for equality test only, where switch statement expression is matched against case labels and the matching case statement is executed.
  •  Value specified with the case is a constant expression.
  • You can’t have two case statements with the same value. Each case label should have a unique value otherwise you will get compile-time error.
  • Value in each case statement must be compatible with the type of the expression in switch statement.
  • With in the Java switch statement default section is optional. If present, conventionally default statement should be the last statement and break statement after the last statement is not required though recommended.
  • Break statement after each case statement is also optional. If break statement is not there after the case then the next case statements are also executed in sequence until the break statement is encountered or all the case statements are executed.

Java switch-case example

public class SwitchExample {
	public static void main(String[] args) {
    int dayOfWeek =5;
    String day;
    switch(dayOfWeek){
      case 1: 
        day = "Sunday";
        break;
      case 2: 			   
        day = "Monday";
        break;
      case 3: 			   
        day = "Tuesday";
        break;
      case 4: 			   
        day = "Wednesday";
        break;
      case 5: 			   
        day = "Thursday";
        break;
      case 6: 			   
        day = "Friday";
        break;
      case 7: 			   
        day = "Saturday";
        break;
      default:
        day = "Invalid value";		   
    }
    System.out.println("Day is- " + day);
  }
}
Output
Day is- Thursday

In the code value for the switch statement’s expression is 5 which matches the case label having the value 5. Since break statement is also there so the switch statement is terminated and the statement after the switch block is executed.

Executing default section in switch statement

In the previous example if dayOfWeek is passed as 10 it won’t match any case statement so the default statement will be executed giving the output as-

Day is- Invalid value

Default section is optional, in the code if the default statement is removed and the dayOfWeek is passed as 10 then no statement will be executed with in the switch block.

public class SwitchExample {
  public static void main(String[] args) {
    int dayOfWeek = 10;
    String day="";
    switch(dayOfWeek){
      case 1: 
        day = "Sunday";
        break;
      case 2: 			   
        day = "Monday";
        break;
      case 3: 			   
        day = "Tuesday";
        break;
      case 4: 			   
        day = "Wednesday";
        break;
      case 5: 			   
        day = "Thursday";
        break;
      case 6: 			   
        day = "Friday";
        break;
      case 7: 			   
        day = "Saturday";
        break;   
    }
    System.out.println("Day is- " + day);
  }
}
Output
Day is-

Java switch-case- Removing break statement

public class SwitchExample {
  public static void main(String[] args) {
    int num = 4;
    switch(num){
      case 1: 
        System.out.println("Passed value is 1");			 
      case 2: 			   
        System.out.println("Passed value is 2");			  
      case 3: 			   
        System.out.println("Passed value is 3");			   
      case 4: 			   
        System.out.println("Passed value is 4");			   
      case 5: 			   
        System.out.println("Passed value is 5");			  
      case 6: 			   
        System.out.println("Passed value is 6");			
      case 7: 			   
        System.out.println("Passed value is 7");			   
      default:
        System.out.println("Passed value doesn't match any value.. ");   
    }
    System.out.println("Out of switch statement..");
  }
}
Output
Passed value is 4
Passed value is 5
Passed value is 6
Passed value is 7
Passed value doesn't match any value.. 
Out of switch statement..

As you can see once the value of the case statement is matched with the expression all the other case statements are also executed in sequence because break statement is not there.

Not having break statement after every case in switch statement doesn’t always create problems, it also gives you a chance to group case statements as shown in the next example.

public class SwitchExample {
  public static void main(String[] args) {
    int dayOfWeek = 2;
    switch(dayOfWeek){
      case 2:			   
           
      case 3: 			   
         
      case 4: 			   
        
      case 5: 			   
        
      case 6: 	
        System.out.println("It's weekday");
        break;
      case 1:
      case 7: 			   
        System.out.println("It's weekend");
        break;   
    }
    System.out.println("Out of switch statement ");
  }
}
Output
It's weekday
Out of switch statement

Using String in Java switch statement

Java 7 onward you can also use expression of type String along with Java switch statement.

public class SwitchExample {
  public static void main(String[] args) {
    String day = "Bangalore";
    String cityCode = "";
    switch(day){
      case "Delhi":
        cityCode = "DEL";
        break;
      case "Lucknow":	
        cityCode = "LKO";
        break;
      case "Bangalore": 	
        cityCode = "BLR";
        break;
      case "Mumbai": 			   
        cityCode = "MUM" ;
        break;
      default:
        cityCode="Not found";
    }
    System.out.println("City code " + cityCode);
  }
}
Output
City code BLR

Enum with Java switch statement

Following Java switch case example shows how to use Enum as an expression with switch statement.

public class SwitchExample {
  public enum Day {Sun, Mon, Tue, Wed, Thu, Fri, Sat}  
  public static void main(String[] args) {
    Day day = Day.Mon;
    switch(day){
      case Sun:
        System.out.println("Day is Sunday");
        break;
      case Mon:	
        System.out.println("Day is Monday");
        break;
      case Tue: 	
        System.out.println("Day is Tuesday");
        break;
      case Wed: 			   
        System.out.println("Day is Wednesday");
        break;
      case Thu: 			   
        System.out.println("Day is Thursday");
        break;
      case Fri: 			   
        System.out.println("Day is Friday");
        break;	
      case Sat: 			   
        System.out.println("Day is Saturday");
        break;
    }
  }
}
Output
Day is Monday

Nested switch statement in Java

You can have a switch-case statement with in the outer switch that is known as nested switch statement.

switch(expression){
  case 1:
  switch(expression){
    case 1: .....
      break;
    case 2 : ....
      break;
    ...
    ...
  }
  break;
}

That's all for the topic Java switch case Statement With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment