Search Your Topic

config
Monday, 15 May 2017 02:44

Java Switch Statement

Written by
Rate this item
(0 votes)

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement.

Syntax:

 
  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

flow of switch statement in java

Example:

 
  1. public class SwitchExample {  
  2. public static void main(String[] args) {  
  3.     int number=20;  
  4.     switch(number){  
  5.     case 10: System.out.println("10");break;  
  6.     case 20: System.out.println("20");break;  
  7.     case 30: System.out.println("30");break;  
  8.     default:System.out.println("Not in 10, 20 or 30");  
  9.     }  
  10. }  
  11. }  

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.

Example:

 
  1. public class SwitchExample2 {  
  2. public static void main(String[] args) {  
  3.     int number=20;  
  4.     switch(number){  
  5.     case 10: System.out.println("10");  
  6.     case 20: System.out.println("20");  
  7.     case 30: System.out.println("30");  
  8.     default:System.out.println("Not in 10, 20 or 30");  
  9.     }  
  10. }  
  11. }  

Output:

20
30
Not in 10, 20 or 30

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Read 396 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training

Facebook