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");
}
}
}
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.
* 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;
break;
default: System.out.println("Wrong choice");
break;
break;
case 9 : System.out.println("Rule 9 is applicable");
break;
break;
case 1 : System.out.println("Rule 6 is applicable");
break;
break;
case 10: System.out.println("Rule 10 is applicable");
break;
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.
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