Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. Java switch statement is used when you have multiple possibilities for the if statement.syntax:
switch(variable) { case 1: //execute your code break; case n: //execute your code break; default: //execute your code break; }

Example of switch statement
public class Sample { public static void main(String args[]) { int a = 5; switch (a) { case 1: System.out.println("You chose One"); break; case 2: System.out.println("You chose Two"); break; case 3: System.out.println("You chose Three"); break; case 4: System.out.println("You chose Four"); break; case 5: System.out.println("You chose Five"); break; default: System.out.println("Invalid Choice. Enter a no between 1 and 5"); break; } } }
Output
You chose Five
Java Switch Statement is fall-through
The java switch statement is fall-through. It means it executes all statement after first match if break statement is not used with switch cases.Example
public class SwitchExample2 { public static void main(String[] args) { int number=30; switch(number) { case 10: System.out.println("10"); case 20: System.out.println("20"); case 30: System.out.println("30"); default:System.out.println("Not in 10, 20 or 30"); } } }
Output
30 Not in 10, 20 or 30