The java case is used with a switch statement the switch statement is another conditional structure. The switch statement is used when we have many choices and we should need only one to be executed we called java case. Nested if it becomes very difficult in such a situation. The switch statement is used when we need to execute multiple cases with multiple conditions. In the switch, case it contains a different block of code and in which is only one executed when the switch value match with a case.
Syntax of java case
switch (variable or an integer expression)
{
case constant:
//Java code block;
case constant:
//Java code block;
case constant:
//Java code block;
default:
//Java code;
}
Example Java Case
int day = 6;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Saturday" (day 6)
Case Statement:
The switch statement (java case) has a different block of conditions and in this situation, we need just one block of code to execute and all of the other condition blocks will be skipped. In the switch statement block condition, we also called Case.
Default Keyword:
The default block appears at the end of all cases. It is executed only when the result of expression does not match with any other case. Its use is optional.
Break Keyword:
The break statement in each case block is used to exit from the switch body. It is used at the end of each case block. When the result of the expression matches a case, the corresponding statements are executed. If the break is not used, all case blocks that come after the matching case will also be executed.
How it’s Work?
- First of all check/evaluated the switch expression
- Then match the switch expression with all cases
- If switch expression matched with any case condition then it’s executed
- If switch expression does not match with any case then all of the other is skipped and the default is run.
Details of switching
- If multiple condition/case is matched with the condition then the first case is selected and execute.
- If the program does not match with any condition/case than the default will automatically execute.
- If the program does not find the default case then switch the statement automatically skipped and go to the next execution.
Browser Support
The following are the browsers are support switch statements.
- Google Chrome
- Internet Explorer
- Opera Browser
- Firefox
- Safari
Visit the java website for more information. Visit
Visit the java tutorial list. And make strong your java concept. Click here. wuschools.com is always written about the CSS concept for the java lover. And writes about how java makes your life easy if you are a web site developer. We help you to continue your learning.