Java switch statement is to choose one or more statement. Switch supports byte, short, char, int, String etc.
We can use if-else-if with multiple condition in place of switch. It will increase the code complexity and readability of code. But, there is an exception with break because of that code free falls to multiple case statements and execute multiple block of code until we find break in switch.
Below is the flow chart which switch follows:
Below is the simple example of switch. We are passing day as an input to switch statement with value 6. As soon as it will match one of the case will run the block code. It will execute default block of code if no case matched.
Break is optional to define for every switch case. If some condition gets true and the break statement is not found for that case. It will run all the subsequent cases until break statement doesn’t find.
Example:
Note: The case 5 got match with the expression. It will print all the days including Default as it doesn’t contain any break statement.
The default code block will run if no condition matches with the switch expression:
Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.
📝 Blogs
javadoubts.com © All rights reserved