Monday 14 March 2016

Switch case puzzle 1

public class CheckInt{
    public static void main(String[] args){
    int choice = 6;
   
    switch(choice){
        case 3 : System.out.println("Rule 3 is applicable");
        default: System.out.println("Wrong choice");
        case 9 : System.out.println("Rule 9 is applicable");
        case 1 : System.out.println("Rule 6 is applicable");
        case 10: System.out.println("Rule 10 is applicable");
    }
}
}

What is the output of the above code ?

OUTPUT :
Wrong choice
Rule 9 is applicable
Rule 6 is applicable
Rule 10 is applicable

REASON :
As you can see the value of choice is 6, and case 6 is not present so default case* statement would be the first to get executed. And since default doesn't have break statement after it prints  "Wrong choice" it would go on executing all the case one by one that follows until it finds break or it comes out of the switch.
* Default case is executed if there is no matching case present and if you haven't written default case in your code then the program gets executed with no output.

Now look at the code below, it contains break statement.

public class CheckInt{
    public static void main(String[] args){
    int choice = 6;
   
    switch(choice){
        case 3 : System.out.println("Rule 3 is applicable");
                 break;
        default: System.out.println("Wrong choice"); 
                 break;
        case 9 : System.out.println("Rule 9 is applicable");
                 break;
        case 1 : System.out.println("Rule 6 is applicable");
                 break;
        case 10: System.out.println("Rule 10 is applicable");
                 break;
    }
}
}

OUTPUT :

Wrong choice

* Change the value of choice as 1 and you will get output as  Rule 6 is applicable.

This Output is the result of break statement.

No comments:

Post a Comment

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.