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.


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.


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

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.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

📝 Blogs

📧 Imran Khan