Explain Codes LogoExplain Codes Logo

Using two values for one switch case statement

java
switch-case
string-objects
java-se-7
Alex KataevbyAlex Kataev·Aug 5, 2024
TLDR

Invoke case fall-through in scenarios where multiple case values yield the same outcome. Use break statements to avoid unintentional fall through and achieve a unified response. A concise example is given below:

int number = 2; switch (number) { case 1: case 2: System.out.println("Number is 1 or 2"); break; // Additional cases... }

This code outputs "Number is 1 or 2" for both cases, hence managing two values with a uniform reply.

Taming the switch statement

Post Java SE 7 upgrade, String objects can be employed within switch expressions. This minor but significant tweak offers a more expressive and refined syntax:

// Who says we can't