Saturday 10 June 2017

Java(switch statement)

                           Switch statement


The java switch statement executes one statement from multiple conditions.
It is like if-else-if ladder statement because in both of them different conditions are to be checked and from the behalf of it,statement would be executed.

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;    
            }    


                                                                                                                                                     
                                     fig: Switch statement




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



Switch statement without break:

If you execute switch statement without break, then it executes all statements after first match.

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



No comments:

Post a Comment