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;
i
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;
}
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;
}
You're better off with the if
statements; the switch
approach is much less clear, and in this case, your switch
approach is objectively wrong. The contract for Comparable#compareTo does not require returning -1
or 1
, just that the value of the returned int
be negative or positive. It's entirely legitimate for compareTo
to return -42
, and your switch
statement would drop the result.
Unfortunately you cannot do that in java. It's possible in CoffeeScript
or other languages.
I would recommend to use an if
-else
-statement by moving your "do stuff" in extra methods. In that way you can keep your if-else in a clearly readable code.
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.
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.