Java : switch statement

Posted in Conditional Statements, Java By Raj On December 9, 2017


Instead of using large series of an if-else-if statement you can use java switch statement, the value which you pass to switch statement is compared with each of the values in the case statement If the value matches any of the case statement then the code will execute which is in the particular case block, if nothing matches then the default block will execute

java switch statement


In the below code we are comparing value 10 to each case statement when it matches to the case statement then call print method to print values

Things we need to remember

  • The  value of case statement should be unique, the case statement will not allow duplicate values
  • The default statement is optional
  • If you want to terminate a program and come out of switch when you are in case block then you need to use break statement
  • The case statement value data type should match switch condition data type 
  • The data type or the expression type the switch statement supports are byte, short, int, char, enum, and string

Example :