SiteMap  | About    

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.


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.



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". 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.


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. (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.