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.

Do you have a Java Problem?
Ask It in The Java Forum

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

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.