A Java method to determine if an integer is between a range

Last night I was writing some Java code for my Android football game, and decided it would be best if I had a between method, so I could write some code like this to show that I wanted to test to see if a number was between an integer range:

if (between(distance, 8, 10)) { ...

That could would be interpreted as, “If the distance is between the values 8 and 10, do whatever is in the code block.” (I can make that code more readable in Scala, but in Java I think that’s the best I can do.)

Solution

In short, I ended up adding the following Java between method to my MathUtils class:

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    if (i >= minValueInclusive && i <= maxValueInclusive)
        return true;
    else
        return false;
}

If you want, you can make that code shorter with the Java ternary operator syntax (which I don’t like), or better yet, like this:

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    return (i >= minValueInclusive && i <= maxValueInclusive);
}

However you want to write it, if you ever need Java source code to determine whether an integer is between a certain range, I hope this code is helpful.