Java switch case
Contents
Syntax : Switch Case in Java Programming
- It is alternative to else-if ladder.
- Switch Case Syntax is similar to - C/C++ Switch.
- Switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression.
- The expression used in the switch statement must return an int, a String, or an enumerated value.
switch (expression) { case value_1 : statement(s); break; case value_2 : statement(s); break; . . . case value_n : statement(s); break; default: statement(s); }
Different Ways of Using Switch Case :
Way 1 : Switch Case Using Integer Case Label
switch (i) { case 1 : System.out.println("One player is playing this game."); break; case 2 : System.out.println("Two players are playing this game."); break; case 3 : System.out.println("Three players are playing this game."); break; default: System.out.println("You did not enter a valid value."); }
Way 2 : Switch Using String
String name = "Pritesh"; switch (name) { case "Pritesh" : System.out.println("One player is playing this game."); break; case "Suraj" : System.out.println("Two players are playing this game."); break; case "Raj" : System.out.println("Three players are playing this game."); break; default: System.out.println("You did not enter a valid value."); }
- If you are coming from C/C++ then you must understand this concept that - Java Supports String Inside Case Label.
- Above program if used in C/C++ then it will give us compile time error.
How Switch Case Statement is different in java from c programming
- In C Programming we were unable to write Case label of data type ‘String’. In java we can have String inside “Switch”.
Live Example 1 : Choose Day of the Week
class SwitchDate{ public static void main(String[] args){ int week = 3; switch (week){ case 1: System.out.println("monday"); break; case 2: System.out.println("tuesday"); break; case 3: System.out.println("wednesday"); break; case 4: System.out.println("thursday"); break; case 5: System.out.println("friday"); break; case 6: System.out.println("saturday"); break; case 7: System.out.println("sunday"); break; default: System.out.println("Invalid week"); break; } } }