Saturday 8 November 2014

Switch case statements in java


Another control statement in java which is equivalent to if and else is switch and case
General structure of switch and case



default block is optional here
Unlike if and else switch executes as follows
Inside switch statement we have given an integer variable and many case statements followed by that.
Now whenever that variable value which we have passed in the switch statements equals the value followed by case key word, then the code which comes under that section executes, and also all other case block codes which follows that including default block.
However any case statement matches or not default block executes by default.
Let's take an example
class switch_demo{
       public static void main(String args[]){
             int a=10;
             switch(a){
                       case 1:
                           System.out.println(“1”);
                       case 2:
                           System.out.println(“2”);
                       case 3:
                             System.out.println(“3”);
                        case 10: 
                                 System.out.println(“10”);
                          case 11:
                                      System.out.println(“11);
                         default:
                                 System.out.println(“100”);
                    }
             }         
}
Find out the output.
Output will be: 10
                        11
                        100
Understand why it is so.

No comments:

Post a Comment