Switch Statement in Java

Switch Statement in Java provides a way to select one option among multiple options.

In Java switch statement it provides multiple case statement  based on switch expression the appropriate case statement is get executed

Syntax of switch statement

The switch expression work with primitive byte short int, char and with its wrapper class, enum type and String Object( added from java7).

case label should also be one the above specified type and it should be constant or literal.

break statement is used to break the execution of switch statement. It transfer control after the switch statement.

If break is not used it execute all cases statement including default followed by currant case statement

The default statement is optional if expression does not match with any label then default case is executed.

Switch does not allows duplicate case value.

Only constants and literals are allowed in case value

Facts About Switch

  • Switch Expression can have primitive byte short int, char and Its Wrapper classes, enum and String Objects.
  • Case values also be one of the type allowed in switch expression.
  • Case value allows only constant and literals.Variables are not allowed.
  • Switch can have any number of case statements in any sequence.
  • Duplicate case statement is not allowed.
  • Default and Break statements is optional
  • If any case expression does not match then default statement is executed.

Switch statement with integer


Switch Statement with Byte Wrapper class


Switch statement character expression


String Object in Switch Statement

From Java 7 String object is added with switch statement


Enum in Switch Statement


Java Switch program to print number of days in month


Java Program to check whether a character is consonant of vowel using switch statement.