The switch statement has the following form:


The 6 things you must remember about the switch statement are:

  1. It works with the following data types: byte/Byte, short/Short, int/Integer, char/Character, String and enum
  2. All case labels should be compile time constants (literals or final variables)
  3. All case constants must be assignable to the type of switch 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 below 127 so they are assignable to byte
  4. All statements after the matching case are executed in sequence (regardless of the expression of subsequent case labels) until a break statement is encountered
  5. switch must have a body. For example: switch (i); doesn’t compile. However an empty body is allowed: switch (i) {}
  6. The default section handles all values not explicitly handled by one of the case. It is optional and can appear anywhere inside the switch block, but only once


Leave a Reply