How to use java switch conditions instead of nested if…else conditions

Switch Statement

We can also use java switch conditions instead of nested if…else conditions to check multiple conditions and execute code accordingly.


Switch Statement

The syntax for the switch statement is as follows.

Switch Statement

If the value/condition matches with any case then the statement inside that case block will be executed. The break inside the case is optional. That is if we remove the break then after the current case all the case blocks will also get executed until any one of them has a “break”. After adding the break no other cases will be checked and switch case will be ended and the cursor will move outside the switch block.

If no cases matched found inside the switch then the default case will be executed.

Example: Example to get day from entered int value.

Switch Statement

In the above example if the user enters 30 or 40 then all output will be as follows :

Entered number is Thirty or Forty
Entered number is Fifty
Matching case not found

Hence if we want to terminate the program after case-matched it’s recommended that we should add a break statement at the end.

If no case is a match like if the user enters 80 then the default case will be executed and the output will be

Matching case not found.

From java7 onwards we can also add a string in a switch statement.

Example:

Switch Statement

Points to be remembered for switch statement:

  1. The break should be used to terminate the statements.
  2. If bread is not added then execution will continue to the next case.
  3. We can add the default statement anywhere, but a break should be added if the default statement is not at the end of the switch.
  4. Variables inside the case are not allowed.
  5. Duplicate cases are not allowed inside the switch.
  6. The type of each case value should be the same as the variable inside the switch.

-A blog by Shwetali Khambe

Related Posts