Core Java

Java Switch Greater Than Or Equal Condition Example

The switch statement in Java is a control flow statement that handles multiple conditions efficiently. However, it is typically used for discrete values, such as integers or enums, rather than range-based conditions like >= (greater than or equal to). Let us understand how the Java switch statement handles the greater than or equal condition.

1. The Issue With Using >= in Switch Statements

Java’s switch statement operates based on exact matches of values rather than conditions. This means you cannot directly use comparison operators like >= in case labels. Consider the following incorrect example:

01
02
03
04
05
06
07
08
09
10
11
12
int score = 85;
 
switch (score) {
    case score >= 90:
        System.out.println("Grade: A");
        break;
    case score >= 80:
        System.out.println("Grade: B");
        break;
    default:
        System.out.println("Grade: C");
}

The above code will not compile because case labels in switch must be constant expressions, not conditions.

2. Different Methods

2.1 Using if-else Statements

The most common approach to handling range-based conditions is using if-else statements. Consider the following example:

01
02
03
04
05
06
07
08
09
10
11
12
13
public class Main {
    public static void main(String[] args) {
        int score = 85;
 
        if (score >= 90) {
            System.out.println("Grade: A");
        } else if (score >= 80) {
            System.out.println("Grade: B");
        } else {
            System.out.println("Grade: C");
        }
    }
}

2.1.1 Code Explanation and Output

The given Java program determines a student’s grade based on their score using an if-else conditional structure. A variable score is assigned a value of 85. The program first checks if score is greater than or equal to 90; if true, it prints "Grade: A". Since 85 is less than 90, it moves to the next condition, checking if score is greater than or equal to 80. As 85 meets this condition, it prints "Grade: B". If neither condition is met, the program would print "Grade: C". In this case, the output is Grade: B.

2.2 Using an Enum with a Custom Method

Another alternative is using an enum with a custom method to determine the category based on ranges. Consider the following example:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
enum Grade {
    A, B, C;
 
    public static Grade getGrade(int score) {
        if (score >= 90) return A;
        else if (score >= 80) return B;
        else return C;
    }
}
 
public class Main {
    public static void main(String[] args) {
        int score = 85;
        Grade grade = Grade.getGrade(score);
 
        switch (grade) {
            case A:
                System.out.println("Grade: A");
                break;
            case B:
                System.out.println("Grade: B");
                break;
            case C:
                System.out.println("Grade: C");
                break;
        }
    }
}

2.2.1 Code Explanation and Output

The given Java program defines an enum called Grade with three values: A, B, and C, representing different grading levels. The getGrade(int score) method determines the grade based on the provided score using conditional statements: scores of 90 or above receive A, scores between 80 and 89 receive B, and scores below 80 receive C. In the main method, a score of 85 is assigned, and getGrade(score) returns B. A switch statement then prints the corresponding grade, resulting in the output: Grade: B.

2.3 Using a Map for Lookup

For a more structured approach, we can use a TreeMap to store ranges. Consider the following example:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
import java.util.NavigableMap;
import java.util.TreeMap;
 
public class Main {
    public static void main(String[] args) {
        NavigableMap<Integer, String> gradeMap = new TreeMap<>();
        gradeMap.put(90, "A");
        gradeMap.put(80, "B");
        gradeMap.put(0, "C");
 
        int score = 85;
        String grade = gradeMap.floorEntry(score).getValue();
 
        System.out.println("Grade: " + grade);
    }
}

2.3.1 Code Explanation and Output

The given Java program uses a TreeMap to determine a grade based on a given score. A NavigableMap<Integer, String> is created and populated with key-value pairs representing score thresholds: 90 -> "A", 80 -> "B", and 0 -> "C". The program assigns a score of 85 and uses floorEntry(score) to find the highest key less than or equal to 85. Since 85 falls between 80 and 90, the closest lower threshold is 80, mapping to grade "B". The program then prints the output: Grade: B.

3. Comparison of different methods

MethodAdvantagesDisadvantages
Using if-else Statements
  • Simple and easy to understand
  • No additional data structures required
  • Becomes complex with multiple conditions
  • Less readable for large condition sets
Using an Enum with a Custom Method
  • Structured and maintains separation of concerns
  • Allows reusability across different parts of the program
  • Requires an additional enum class
  • Slightly more complex for beginners
Using a TreeMap for Lookup
  • Efficient for predefined ranges
  • Makes adding new conditions easier
  • Overhead of maintaining a TreeMap
  • May be unnecessary for small datasets

4. Conclusion

Since Java’s switch statement does not support relational operators like >=, alternative approaches are needed for handling range-based conditions. The best alternatives include using if-else statements for simple logic, using an enum with a helper method for structured decision-making, or using a TreeMap for efficient lookups when dealing with predefined ranges. By choosing the right approach, developers can handle range-based conditions effectively while maintaining clean and efficient code.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button