The switch statement has the following form:
1 2 3 4 5 6 7 8 |
switch (expression) { [case constant1: statement_or_block [break;]] [case constant2: statement_or_block [break;]] … [default: statement-or-block [break;]] } |
Example:
1 2 3 4 5 6 7 8 |
byte b = 'a'; switch (b) { case 97: System.out.println("a"); break; case 98: System.out.println("b"); break; default: System.out.println("c"); } |
The 6 things you must remember about the switch
statement are:
- It works with the following data types:
byte
/Byte
,short
/Short
,int
/Integer
,char
/Character
,String
andenum
- All
case
labels should be compile time constants (literals or final variables) - All
case
constants must be assignable to the type ofswitch
expression (you’ll get a compiler error if they aren’t). Note that'a'-'z'
,'A'-'Z'
and'0'-'9'
are all constants with a value below127
so they are assignable to byte - All statements after the matching
case
are executed in sequence (regardless of the expression of subsequentcase
labels) until abreak
statement is encountered switch
must have a body. For example:switch (i);
doesn’t compile. However an empty body is allowed:switch (i) {}
- The
default
section handles all values not explicitly handled by one of thecase
. It is optional and can appear anywhere inside theswitch
block, but only once