1

For example say I want to check if a value is greater than or equal to x, but less than or equal to y.

I figured I just needed to use the logical "and" operator like this:

if(value >= x && value <= y) {
   do something
}

and it worked, but I'm curious to know if there are other methods of achieving the same result.

Uma
  • 33
  • 9
  • 1
    Possible duplicate of [Check if int is between two numbers](http://stackoverflow.com/questions/1992970/check-if-int-is-between-two-numbers) – Imbar M. Sep 19 '16 at 23:03

4 Answers4

2

There are other ways, as other answers indicate - but your way is totally canonical.

It is:

  • clear
  • requires no external referencing or familiarity with external APIs
  • as efficient as you can possibly get - and it's manifestly efficient, in the sense that I don't have to go guessing about inlining and other Hotspot magic, and has no conditionals to make my railway run badly
  • free from confusion over open/closed ranges: I can see that it's an all inclusive range, and if you wanted to change that, it's a one char change (imagine figuring that out with the Math.min/max version!)

It's beautiful. Don't change it.

Community
  • 1
  • 1
SusanW
  • 1,550
  • 1
  • 12
  • 22
  • My note about "no conditionals" - and I'm talking about causing branch-prediction failures - is questionable: the && lazy evaluation of the RHS does involve a branch. But I'd guess it's more efficient _in this simple case_ to do the RHS regardless, rather than risk a prediction fail. I wonder if Hotspot makes such a determination? I feel an experiment is being born! Thoughts anyone? – SusanW Sep 19 '16 at 23:52
1

You could use Guava's Range:

if (Range.closed(x, y).contains(value))

There's really no point with ints (especially considering autoboxing), but it can be useful for other Comparable values.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • This is nice when `value` is a more complicated expression than just an `int`, where you would otherwise need to store the expression in a temporary variable. Also nice when the `Range` is set up elsewhere and you really want to represent the `x`,`y` values specifically as a range interval. – SusanW Sep 20 '16 at 11:04
0

Another way will be using Java.lang.Math library.

Math.max(Math.min(value, max), min) == value
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
0

Consider creating your own static utility classes for just such things.

public final class IntUtil
{
    // ...

    public static boolean isBetween(int value, int min,int max)
    {
        return value >= min && value <= max;
    }

    // ...
}
GregorMohorko
  • 2,739
  • 2
  • 22
  • 33