Reputation: 24474
How can I do something like:
int a=5;
if(4<=a<=6){
}
in Java?
Upvotes: 1
Views: 4860
Reputation: 533530
You can do this. Its ugly, but can be very slightly faster.
int a = 5;
if(a - Integer.MIN_VALUE - 4 <= 2 - Integer.MIN_VALUE) {
}
This exploits the use of underflow to turn two comparisons into one. This can save about 1-2 nano-seconds. However, in some usecases it can cost the same amount, so only try it if you are trying to micro-tune a loop.
Upvotes: 1
Reputation: 19551
if(4 <= a && a <= 6) {
// do something
}
Of course, you could always write a function like this in some Util
class:
class Util {
public static boolean inclusiveBetween(int num, int a, int b) {
return num >= a && num <= b;
}
}
and then you can do something like
if(Util.inclusiveBetween(someResourceIntensiveOpReturningInt(), 4, 6)) {
// do things
}
Upvotes: 3
Reputation: 597106
Apart from the obvious solution stated by others (if(4<=a && a<=6)
), you can use commons-lang's IntRange
:
Range range = new IntRange(4,6)
if (range.containsInteger(5)) {..}
It looks like a bit of an overkill, but depending on the situation (if it isn't as trivial) it can be very useful.
Upvotes: 5
Reputation: 224921
You can't, I don't think. What's wrong with
int a = 5;
if(a >= 4 && a <= 6) {
}
? If you need to compare many different variables, put them in an array and sort the array, then compare the arrays.
Upvotes: 2