Three keywords: switch, case and default
int action = ...; // a certain value from 1 to 3
if (action == 1) {
System.out.println("Starting a new game...");
} else if (action == 2) {
System.out.println("Loading a saved game");
} else if (action == 3) {
System.out.println("Displaying help...");
} else if (action == 4) {
System.out.println("Exiting...");
} else {
System.out.println("Unsuitable action, please, try again");
}
Of course, this code handles the task. But if your conditional statement has a lot of branches, it can be hard to understand.
switch (action) {
case 1:
System.out.println("Starting a new game...");
break;
case 2:
System.out.println("Loading a saved game");
break;
case 3:
System.out.println("Displaying help...");
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Unsuitable action, please, try again");
}
As you may note, this code is well-structured and easier to read than the equal conditional statement.
The general form of the switch statement
switch (variable) {
case value1:
// do something here
break;
case value2:
// do something here
break;
//... other cases
case valueN:
// do something here
break;
default:
// do something by default
}
The switch
and case
keywords are always required here. The keywords break
and default
are optional. The keyword break
stops the execution of the whole switch statement, not just one case.
If a case does not have the break-
keyword, the following case will be also evaluated. The default
case is evaluated if no any case matches the variable value.
An example with "zero", "one" and "two"
Let's consider another example. The following code outputs the names of integer numbers or a default text. It has three base cases and one default case.
int val = ...;
switch (val) {
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
break;
case 2:
System.out.println("two");
break;
default:
System.out.println("The value is less than zero or greater than two");
}
If the val
is 0, the code prints:
zero
If the val
is 1, the code prints:
one
if the val
is 10, the code prints:
The value is less than zero or greater than two
If you forget the keyword break
in a case, the compiler won't consider it an error. Let's remove it from the second case (case 1) and assign 1 to val
. The program prints:
one
two
Omitting
break
keyword is not a good practice. Try to avoid it.