Java Switch

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:

Switch Rules:

  1. The switch statement will evaluate only once on execution.
  2. Multiple case be written per switch statement.
  3. The value of expression will compare with each case case.
  4. Case cannot have the duplicate value.
  5. The break and default keywords are optional.

Example:

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.

The break keyword:

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 keyword:

The default code block will run if no condition matches with the switch expression:

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0