This keyword is part of a switch
. A case's inner statements are executed when the value switched upon has the value of the case. We can use final values and constants in cases.
Strings, ints, and chars are some of the variable types we can match in a case. A case usually has a break
or return at its end. But if it does not, it falls through to the next case.
This example uses many case statements. It stacks cases, which means multiple values (100, 1000, or 10000 for example) all match the same statement block.
string
in this example) can be matched in a case.break
or return) so it falls through and also matches case "Y."public class Program { static String testCase(String value) { final String special = "constant"; String temp = ""; // Switch on the String value. switch (value) { case "100": case "1000": case "10000": { // Place braces around case statements. return "Multiple of ten"; } case "500": case "5000": case "50000": // No braces are needed. return "Multiple of fifty"; case special: // We can match a final constant. // ... Multiple statements can be in a case. String result = special.toUpperCase() + "!"; return result; case "cat" + "100": // This also matches a constant. // ... The string expression is compiled into a final String. return "CAT"; case "X": // This case will fall through so case "Y" is also entered. temp += "X"; case "Y": temp += "Y"; return temp; default: // The default case. return "Invalid"; } } public static void main(String[] args) { System.out.println(testCase("100")); System.out.println(testCase("1000")); System.out.println(testCase("5000")); System.out.println(testCase("constant")); System.out.println(testCase("cat100")); System.out.println(testCase("X")); System.out.println(testCase("Y")); System.out.println(testCase("?")); } }Multiple of ten Multiple of ten Multiple of fifty CONSTANT! CAT XY Y Invalid
A case must have a constant value. If we try to use a local variable like an int
that is not constant in a case, we will get a compilation error.
public class Program { public static void main(String[] args) { int value = 100; int bird = 10; // This is an error: we must have a constant case. switch (value) { case bird: break; } } }Exception in thread "main" java.lang.Error: Unresolved compilation problem: case expressions must be constant expressions at Program.main...
In switch
statement and cases, we have an opportunity to increase our program quality by adding symmetry. Each case can be seen as a separate but equal path.
The case keyword in Java can handle constants (finals) and constant expressions. Default too is a case, but it omits the "case" keyword.