Java Switch Case Control Statements with Program Examples

In this tutorial we will study and understand the working of Java Switch Case Control Statements and take a few examples. We will also understand the working and when to use Switch case and when to use the If-Else statement.

Java Switch Case Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. It is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be byte, short, char, and int primitive data types.

Java Switch Case

Syntax –
switch(value){    
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;    
}
Program Example –
public class SwitchExample {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    case 10: System.out.println("10");break;  
    case 20: System.out.println("20");break;  
    case 30: System.out.println("30");break;  
    default:System.out.println("Not in 10, 20 or 30");  
    }  
}  
}
Output
20
Java Switch Statement is fall-through

The java switch statement is fall-through. It means it executes all statement after first match if break statement is not used with switch cases.

Program Example –
public class SwitchExample2 {  
public static void main(String[] args) {  
    int number=20;  
    switch(number){  
    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
Some Points to remember about Switch Case –
  • Switch case only operates with values and not expressions.
  • Switch case is fall through (you just saw that example above)
  • Switch case works only with Integral datatypes – short, byte, int, char and not with any other type like float, string etc.
Watch it on YouTube

Leave a Reply

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