How to Use OR Operator in a Java Switch-Case Statement

Published Dec 28, 2021  ∙  Updated May 2, 2022

How can we logically create an OR condition in a Java switch statement?

Example scenario

Suppose we have a switch statement in Java.

int i = /* some integer */;
switch(i) {
  case 1: 
    break; // do something with 1
  case 2: 
    break; // do something with 2
  case 3: 
    break; // do something with 3
  case 4: 
    break; // do something with 4
  /* ... */
}

How can we create an OR condition using the switch statement?

Use OR operator by removing break

We can logically create an OR statement by omitting the break lines.

Any case without a break line will trigger the switch-case fallthrough, during which the control flow will be directed to the next case line.

int i = /* some integer */;
switch(i) {
  case 1: 
  case 2: 
    break; // 1 or 2
  case 3: 
  case 4: 
    break; // 3 or 4
  /* ... */
}