Home >Java >javaTutorial >How Can I Handle Value Ranges in Java\'s Switch Statement?

How Can I Handle Value Ranges in Java\'s Switch Statement?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 03:28:08582browse

How Can I Handle Value Ranges in Java's Switch Statement?

Switch Statement with Value Ranges in Java

In Java, it's not possible to specify a range of values in a single case of a switch statement. The code example provided below won't work:

switch (num) {
    case 1 .. 5:
        System.out.println("testing case 1 to 5");
        break;
    case 6 .. 10:
        System.out.println("testing case 6 to 10");
        break;
}

Unlike Objective C, which supports ranges in switch statements, Java does not have such functionality. As an alternative, consider using if-else if statements:

if (isBetween(num, 1, 5)) {
    System.out.println("testing case 1 to 5");
} else if (isBetween(num, 6, 10)) {
    System.out.println("testing case 6 to 10");
}

Here, isBetween() is a helper method that checks if a number falls within a specified range:

public static boolean isBetween(int x, int lower, int upper) {
    return lower <= x && x <= upper;
}

By using if-else if statements, you can evaluate multiple ranges and execute the appropriate block of code.

The above is the detailed content of How Can I Handle Value Ranges in Java\'s Switch Statement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn