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: