How to use greater than or equal in a switch statement

86,199

Solution 1

Not sure if this is what you're asking, but you could do it this way:

int var1;
int var2;

int signum = Long.signum((long)var1 - var2);
switch(signum) {
    case -1: break;
    case 0: break;
    case 1: break;
}

Solution 2

I would strongly recommend a if(var1>var2){}else if (var1==var2) {} else {} construct. Using a switch here will hide the intent. And what if a break is removed by error?

Switch is useful and clear for enumerated values, not for comparisons.

Solution 3

First a suggestion: switch as it states should only be used for switching and not for condition checking.

From JLS switch statements

SwitchStatement:
    switch ( Expression ) SwitchBlock

Expressions convertible to int or Enum are supported in the expression.

These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) or enum constants (§8.9.1) in the case labels.

Only constant expressions and Enum constants are allowed in switch statements for 1.6 or lower with java 7 String values are also supported. No logical expressions are supported.

Alternatively you can do as given by @Stewart in his answer.

Solution 4

Java only supports direct values, not ranges in case statements, so if you must use a switch, mapping to options first, then switching on that, as in the example you provide is your only choice. However that is quite excessive - just use the if statements.

Solution 5

A switch statement is for running code when specific values are returned, the if then else allows you to select a range of values in one statement. I would recommend doing something like the following (though I personnally prefer the Integer.signum method) should you want to look at multiple ranges:

int i;

if (var1 > var2) {
  i = 1;
}
else if (var1 == var2) {
  i = 0;
}
else {
  i = -1;
}
Share:
86,199

Related videos on Youtube

Vlad Holubiev
Author by

Vlad Holubiev

💻 AWS, Cloud, Serverless, Microservices, node.js, Docker, Elasticsearch, MongoDB, APIs, IaaC, CI, DevOps, TDD, Terraform, Jest 🌐 Website: vladholubiev.com 💬 Twitter: twitter.com/vladholubiev ✏️ Blog: medium.com/@vladholubiev 💼 LinkedIn: linkedin.com/in/vlad-holubiev

Updated on March 02, 2020

Comments

  • Vlad Holubiev
    Vlad Holubiev about 4 years

    What is the best way to check if variable is bigger than some number using switch statement? Or you reccomend to use if-else? I found such an example:

    int i;
    
    if(var1>var2) i = 1;
    if(var1=var2 i = 0;
    if(var1<var2) i = -1;
    
    switch (i);
    {
        case -1:
        do stuff;
        break;
    
        case 0:
        do stuff;
        break;
    
        case 1:
        do stuff;
        break;
    
    }
    

    What can you tell a novice about using "greater than or equal" in switch statements?

    • SJuan76
      SJuan76 over 10 years
      I would say it will be clearer with 3 if
    • Mattsjo
      Mattsjo over 10 years
      I can't see why you'd use a switch statement if you've already got an if statement. Just do it with if statements since the logic is already there
    • Kevin DiTraglia
      Kevin DiTraglia over 10 years
      You are better off with an if-else
  • emory
    emory over 10 years
    Basically true. However in some cases (not the OP's case), the default option can be used to effectively support a range.
  • Stewart
    Stewart over 10 years
    If var1 == 6 and var2 == 4, then var1 - var2 == 2 which isn't in your switch. You need to use Integer.signum() as per my answer 5 mins ago. :)
  • treeno
    treeno over 10 years
    This is very short code, but I'm not sure if this is easy readable for everyone (including myself). I think it is more important to have code that is easy readable if that code will be maintained by many poeple for a long period of time.
  • Narendra Pathai
    Narendra Pathai over 10 years
    +1 for using switch and I have updated my answer. Thanks for pointing that out.
  • Holger
    Holger over 10 years
    Not recommended due to the risk of numerical overflow. It can take hours to find the bug.
  • Stewart
    Stewart over 10 years
    @treeno - To be honest, I agree with you. It's just the question was specifically about switch statements. Although I can imagine some situations where numeric ranges passing thresholds might want to be converted into a "banded" approach - for example temperature being above or below or within a specific range, or a bank account being in credit, overdrawn, or overdrawn beyond overdraft limit.
  • Holger
    Holger over 10 years
    And with signum it’s still broken as the difference can be higher than the integer range yielding to an overflow and wrong results.
  • Stewart
    Stewart over 10 years
    @Holger - Could you expand on that please?
  • Holger
    Holger over 10 years
    The distance between Integer.MIN_VALUE and Integer.MAX_VALUE is two times the integer range. So if one value is very large and the other very small the distance does not fit within an integer and an overflow occurs resulting in the wrong sign.
  • Stewart
    Stewart over 10 years
    @Holger - Good point. I'll edit to use Long.signum() instead :-)
  • HesNotTheStig
    HesNotTheStig over 4 years
    I've frequently used the signum switch approach to avoid two comparisons. Do you suppose it's FASTER than doing two comparisons?
  • Stewart
    Stewart over 4 years
    @HesNotTheStig Actually, the OP case has 3 comparisons, not just 2. As for faster, maybe this answer helps, including the reference code? stackoverflow.com/a/13988826/167745
  • HesNotTheStig
    HesNotTheStig over 4 years
    Yeah, but if you're doing the if/else method, you really only need two comparisons (assuming you're dealing with integral values).