Java Switch Statement

The switch statement is used to perform different actions based on different conditions. Java switch statement works with the byte, short, char, and int primitive data types. It also works with enumerated types , the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer. Syntax:
switch(expression) { case n: code block break; case n: code block break; default: default code block }
The switch expression (condition)is evaluated once and the value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. If no matching case clause is found, the program looks for the optional default clause , and if found, transfers control to that clause, executing the associated statements. The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement. Example:
class TestClass { public static void main (String[] args) { int inDay = 2; String day; switch (inDay) { case 1: day = "Subday"; break; case 2: day = "Monday"; break; case 3: day = "Tuesday"; break; case 4: day = "Wednesday"; break; case 5: day = "Thursday"; break; case 6: day = "Friday"; break; case 7: day = "Saturday"; break; default: day = "Invalid entry"; break; } System.out.println("Selected day is: " + day); } }
Output:
Selected day is: Monday

In the above case, inDay is the parameter to switch. Depends on switch parameter the day string is assigned the corresponding value. Here inDay=2, so the switch assign day="Monday".

switch..case on a String

How to switch statement on Java String Switch statements with String cases have been implemented in Java SE 7 , at least 16 years after they were first requested. A clear reason for the delay was not provided, but it likely had to do with performance.
class TestClass { public static void main (String[] args) { String inGrade = "A"; String message; switch (inGrade) { case "A+": message = "Excellent !!"; break; case "A": message = "Very Good !!"; break; case "B": message = "Good !!"; break; case "C": message = "Passed !!"; break; case "D": message = "Failed !!"; break; default: message = "Invalid entry"; break; } System.out.println(message); } }
Output:
Very Good !!
Switches based on integers can be optimized to very efficient code. Switches based on other data type can only be compiled to a series of if() statements . For that reason C & C++ only allow switches only on integer types.