Java Certification, Programming, JavaBean and Object Oriented Reference Books
Java switch Statement

This tutorial will take you step by step through the process of understanding and using the control statement switch. The best way to learn is to compile and run these programs yourself (copy, paste, compile and run !). Comments such as /* this is a comment */ or // this is another comment are inserted to explain what does the line of code do. The programs are kept simple for the purpose of concentrating on the main idea in question.

Example 1: simple switch statement

The statement associated with case constatnt gets executed.

  
class Switch1{ 
   public static void main(String args[]){
      int k = 10;

      switch(k){
         case 5: System.out.println(" case k = 5"); 
         break;
         case 10: System.out.println(" case k = 10"); 
         break;
         case 15: System.out.println(" case k = 15"); 
         break;
         default: System.out.println(" case default"); 
      }
   }
}      

The output is case k = 10.

NOTE:

1- default statement is executed if no case statements match.

2- the break takes control out of the block; if it is omitted, execution continues to the next case.(see the example below)

Example 2: no break between cases 10 and 15

The statement associated with case constatnt gets executed.

  
class Switch2{ 
   public static void main(String args[]){
      int k = 10;

      switch(k){
         case 5: System.out.println(" case k = 5"); 
         break;
         case 10: System.out.println(" case k = 10"); 
         case 15: System.out.println(" case k = 15"); 
         break;
         default: System.out.println(" case default"); 
      }
   }
}      

The output is case k = 10 case k = 15, this occurs because the break statement was omitted.

Return to : Java Programming Hints and Tips