yydl
yydl

Reputation: 24474

Java - Double Comparison

How can I do something like:

int a=5;
if(4<=a<=6){

}

in Java?

Upvotes: 1

Views: 4860

Answers (5)

Peter Lawrey
Peter Lawrey

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

Aaron Yodaiken
Aaron Yodaiken

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

Bozho
Bozho

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

Ry-
Ry-

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

corsiKa
corsiKa

Reputation: 82579

Make it two conditions:

int a=5;
if(4<=a && a<=6){

}

Upvotes: 7

Related Questions