«Back to Home

Core Java

Topics

Switch Statement In Java

Switch statement

Java switch statement is also a control flow statement. It is used when we want to be tested for equality against a list of the values. Switch statement returns one statement from the multiple conditions.
 
Syntax

switch(expression){
case value1:
// code.
break; //it is not compulsory(Optional).
case value2;
// code.
break;
.
.
default:
// code..
}
 
Let’s understand with the flowchart, given below.

58

Let’s see an example, given below.
 
Code
  1. public class SwitchStatement {  
  2.     public static void main(String args[]) {  
  3.         char grade = 'C';  
  4.         switch (grade) {  
  5.             case 'A':  
  6.                 System.out.println("Excellent");  
  7.                 break;  
  8.             case 'B':  
  9.                 System.out.println("Very Good");  
  10.                 break;  
  11.             case 'C':  
  12.                 System.out.println("Good");  
  13.                 break;  
  14.             case 'D':  
  15.                 System.out.println("Passed");  
  16.             case 'F':  
  17.                 System.out.println("Better try again");  
  18.                 break;  
  19.             default:  
  20.                 System.out.println("Invalid ");  
  21.         }  
  22.         System.out.println("Your grade is " + grade);  
  23.     }  
  24. }  
44
 
Output 

45
 
Switch Statement if fall-through

This switch statement if fall-through is used when we want to return all the statement after first matching case and if break statement is not used with the cases.
 
For example.
 
Code
  1. public class SwitchStatement2 {  
  2.     public static void main(String[] args) {  
  3.         char letter = 'B';  
  4.         switch (letter) {  
  5.             case 'A':  
  6.                 System.out.println("A");  
  7.             case 'B':  
  8.                 System.out.println("B");  
  9.             case 'C':  
  10.                 System.out.println("C");  
  11.             default:  
  12.                 System.out.println("Not in A, B or C");  
  13.         }  
  14.     }  
  15. }  
46
 
Output

47
 
Summary

Thus, we learnt “switch statement” is used when we want to be tested for the equality against a list of the values and also learnt how to use it in Java.