When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement
code block, you must insert a break statement, which causes the
program to continue executing after the current code block.
SYNTAX
switch
(expression)
{
case
value-
1
:
block-
1
break
;
case
value-
2
:
block-
2
break
;
default
:
default
-block
break
;
}
rest-of-code;
FLOW CHART:
EXAMPLE PROGRAM:
public class SwitchCaseStatementDemo {
public static void main(String[] args)
{
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c)
{
status = 1;
}
else if (b > c)
{
status = 2;
}
else
{
status = 3;
}
switch (status) {
case 1:
System.out.println("a is the greatest");
break;
case 2:
System.out.println("b is the greatest");
break;
case 3:
System.out.println("c is the greatest");
break;
default:
System.out.println("Cannot be determined");
}
}
}
Output
c is the greatest