Search code examples
javaoperatorsswitch-statementrelational

use relational operators in switch


Is there a way to use relational operators (<,<=,>,>=) in a switch statement?

int score = 95;

switch(score)  {
   case (score >= 90):
      // do stuff
}

the above example (obviously) doesn't work


Solution

  • No you can not.
    From jls-14.11

    The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.  
    

    Relational operators (<,<=,>,>=) results in boolean and which is not allowded.

    All of the following must be true, or a compile-time error occurs:

    • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

    • No two of the case constant expressions associated with a switch statement may have the same value.

    • No switch label is null.

    • At most one default label may be associated with the same switch statement.