Java switch Statements
Jakob Jenkov |
A Java switch statement enables you to select a set of statements to execute based on the value of some variable. This is in effect somewhat similar to a Java if statement, although the Java switch statement offers a somewhat more compressed syntax, and slightly different behaviour and thus possibilities. In this Java switch tutorial I will explain both how the original Java switch instruction works, as well as the modifications to the switch instruction with the ability to switch on Java enums, Java Strings, and finally the new switch expression syntax that was added in Java 12 and improved in Java 13.
Java Switch Video Tutorials
If you prefer video, I have created two videos that explain the basic Java switch
statement
and the Java switch
expressions.
Java Switch Statement Example
Let us start with a Java switch
statement code example:
int amount = 9; switch(amount) { case 0 : System.out.println("amount is 0"); break; case 5 : System.out.println("amount is 5"); break; case 10 : System.out.println("amount is 10"); break; default : System.out.println("amount is something else"); }
This switch example first creates a variable named amount
and assigns the value 9
to it.
Second, the example "switches" on the value of the amount
variable. Inside the switch
statement are 3 case
statements and a default
statement.
Each case
statement compares the value of the amount
variable with a constant value. If the amount
variable value is equal to that constant value, the code after the colon (:) is executed. Notice the break
keyword after each statement. If no break
keyword was place here, the execution could continue down
the rest of the case
statements until a break
is met, or the end of the switch
statement is reached. The break
keyword makes execution jump out of the
switch
statement.
The default
statement is executed if no case
statement matched the value of the amount
variable. The default
statement could
also be executed if the case
statements before it did not have a break
command in the end.
You don't need a default
statement. It is optional.
The if Statement Equivalent
The Java switch example shown in the beginning is equivalent to the following set of Java if statements:
int amount = 9; if (amount == 0) { System.out.println("amount is 0"); } else if(amount == 5) { System.out.println("amount is 5"); } else if(amount == 10){ System.out.println("amount is 10"); } else { System.out.println("amount is something else"; }
While it looks almost the same, there are situations where using a Java switch statement is easier, and faster. Also, the new Java switch expression added in Java 12 (see later in this tutorial) makes some constructs possible with a switch statement that are not possible with an if-statement.
Switch on Parameters
In the example shown in the beginning of this Java switch tutorial we declared an int
variable
and immediately set is value to 9. In a real life Java application you would most likely not do that. Instead you
would be switching on the value of an input parameter of a method, or on a value read from a file, over the network
etc. Here is an example of switching on a method parameter:
private static void switchOnIntegers(int size) { switch(size) { case 0 : { System.out.println("size is small"); break; } case 1 : { System.out.println("size is medium"); break; } case 2 : { System.out.println("size is large"); break; } case 3 : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
Switch on byte, short, char, int, String, or enum's
As you have seen, the switch statement switches on a variable. Before Java 7 this variable has to be numeric and must
be either a byte
, short
, char
or int
. From Java 7 the variable
can also be a String
It is also possible switch on a Java enum variable. In the following sections I will
show you examples of how to switch on various different Java types.
Switch on byte, short and int
You can switch on a Java byte
, short
or int
as shown in the following
examples:
private static void switchOnIntegers(byte size) { switch(size) { case 0 : { System.out.println("size is small"); break; } case 1 : { System.out.println("size is medium"); break; } case 2 : { System.out.println("size is large"); break; } case 3 : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
private static void switchOnIntegers(short size) { switch(size) { case 0 : { System.out.println("size is small"); break; } case 1 : { System.out.println("size is medium"); break; } case 2 : { System.out.println("size is large"); break; } case 3 : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
private static void switchOnIntegers(int size) { switch(size) { case 0 : { System.out.println("size is small"); break; } case 1 : { System.out.println("size is medium"); break; } case 2 : { System.out.println("size is large"); break; } case 3 : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
Notice that the only thing that is different between the above examples is the data type of the method parameter
size
. Everything else is the same.
Switch on char
It is also possible to switch on a Java char
value. Here is an example of switching on a
char
parameter:
private static void switchOnChars(char size) { switch(size) { case 'S' : { System.out.println("size is small"); break; } case 'M' : { System.out.println("size is medium"); break; } case 'L' : { System.out.println("size is large"); break; } case 'X' : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
Switch on String
From Java 7 and forward it is possible to use switch on a Java String too.
Here is an example of a Java switch on a String
:
private static void switchOnStrings(String size) { switch(size) { case "S" : { System.out.println("size is small"); break; } case "M" : { System.out.println("size is medium"); break; } case "L" : { System.out.println("size is large"); break; } case "XL" : { System.out.println("size is X-large"); break; } default : { System.out.println("size is not S,M,L or XL: " + size); } } }
Switch on Java Enum
It is also possible to switch on a Java enum. Here is a Java example that creates a
Java enum
and then uses it in a switch statement:
public class SwitchOnEnum{ private static enum Size { SMALL, MEDIUM, LARGE, X_LARGE } private static void switchOnEnum(Size size) { switch(size) { case SMALL : { System.out.println("size is small"); break; } case MEDIUM : { System.out.println("size is medium"); break; } case LARGE : { System.out.println("size is large"); break; } case X_LARGE : { System.out.println("size is X-large"); break; } default : { default : { System.out.println("size is not S,M,L or XL: " + size); } } } } }
Multiple case statements for same operation
In case you want the same operation executed for multiple case
statements, you write it like
this:
char key = '\t' switch(key) { case ' ' : case '\t' : System.out.println("white space char"); break; default : System.out.println("char is something else"); }
Notice how the first case
statement does not have any operation after the colon. The result of
this is, that execution just "falls through" to the operation of the next case statement ( and the next etc.)
until a break
is met. The next break
statement is after the second case
statement.
That means, that for both the first and second case
statement, the same operation is executed - that
of the second case
statement.
Multiple Values Per Case Statement
From Java 13 and forward you can also have multiple values per case
statement, instead of
having multiple case statements falling through to the next. Here is the example from the previous section
rewritten to use multiple values in a single state
statement:
char key = '\t' switch(key) { case ' ', '\t' : System.out.println("white space char"); break; default: System.out.println("char is something else"); }
Notice how the multiple values for the first case statement are separated by a comma.
Java switch Expressions
Java 12 added the switch expression as experimental feature. A Java switch expression a switch statement which can return a value. Thus, it can be evaluated as an expression, just like other Java expressions (which are also evaluated to a value). In this section I will show you how the Java switch expressions of Java 12 works.
Remember, I have a video version of the Java switch
expression part of this tutorial here:
Here is first a Java switch expression example:
int digitInDecimal = 12; char digitInHex = switch(digitInDecimal){ case 0 -> '0'; case 1 -> '1'; case 2 -> '2'; case 3 -> '3'; case 4 -> '4'; case 5 -> '5'; case 6 -> '6'; case 7 -> '7'; case 8 -> '8'; case 9 -> '9'; case 10 -> 'A'; case 11 -> 'B'; case 12 -> 'C'; case 13 -> 'D'; case 14 -> 'E'; case 15 -> 'F'; default -> '?'; }; System.out.println(digitInHex);
This Java switch
expression example converts a value between 0 and 15 to a hexadecimal digit character.
Notice how the colon (:
) after each case
statement has been replaced with a
->
operator. This operator is used inside of switch expressions to signal to the Java compiler
that this case
statement selects a return value for the switch expression, rather than selecting
a block of code to execute.
Notice also, that the case
statements have no break
keyword after them. Since the value
selected with the ->
operator is interpreted as the return value of the switch expression, the
break
after each statement is implicit (unnecessary actually). You can also think of the
->
as a return
statement which returns a value from the switch expression, and thus
breaks the execution of the switch expression.
Finally, notice how the digitInHex
variable is assigned the return value of the
switch
expression. This is how you capture the output of a Java switch expression. You could also
have returned its value as a return value from a method, like this:
public char toHexDigit(int digitInDecimal) { return switch(digitInDecimal){ case 0 -> '0'; case 1 -> '1'; case 2 -> '2'; case 3 -> '3'; case 4 -> '4'; case 5 -> '5'; case 6 -> '6'; case 7 -> '7'; case 8 -> '8'; case 9 -> '9'; case 10 -> 'A'; case 11 -> 'B'; case 12 -> 'C'; case 13 -> 'D'; case 14 -> 'E'; case 15 -> 'F'; default -> '?'; }; }
The Java switch expression also works with Java String values. Here is a Java switch expression example using Strings to switch on:
String token = "123"; int tokenType = switch(token) { case "123" -> 0; case "abc" -> 1; default -> -1; };
This example resolves a token type (integer value) based on the values of a String token.
Java switch yield Instruction
From Java 13 you can use the Java switch yield instruction to return a value from a Java switch expression instead
of using the arrow operator (->
). Here is an example of the Java switch yield instruction looks:
String token = "123"; int tokenType = switch(token) { case "123" : yield 0; case "abc" : yield 1; default : yield -1; };
switch Expression Use Cases
The Java switch expressions are useful in use cases where you need to obtain a value based on another value. For instance, when converting between number values and characters, as shown in the example above.
Java switch expressions are also useful when parsing characters into values, or String tokens into integer token types. In general, whenever you need to resolve one value to another.
Tweet | |
Jakob Jenkov |