Of course, there is nothing wrong with
return (i >= lo && i <= hi);
And, as @Holger pointed out in a comment,
return (foo >= 0);
is sufficient, if hi=Integer.MAX_VALUE;
It might look more efficient, to do bitshifting, but I doubt it:
return (i >> 31) == 0;
@ScArcher suggested a general class, which is fine for 2011, but could nowadays been implemented with a record, saving us 5 lines of code while giving us a nice toString and hashCode and equals-method for free. And while we're already probably overengineering this thing, let's use a Lambda Predicate (which cost us the addiditional line for the import:
import java.util.function.*;
public record InRange (int lo, int hi) implements IntPredicate {
public boolean test (int i) {
return i >= lo && i <= hi;
}
}
// usage:
InRange posInt = new InRange (0, Integer.MAX_VALUE);
posInt.test (42); // true
posInt.test (-42); // false
List.of (Integer.MIN_VALUE, -2, -1, 0, 1, 2, Integer.MAX_VALUE).stream ().filter (posInt::test).toList();
$71 ==> [0, 1, 2, 2147483647]
ifstatement wins. I agree, though, that this observation shouldn’t drive your decision. For 99 % of applications, maintenance efficiency will be more important.if(foo >= 0) …, as there’s no need to check whether anintis<=Integer.MAX_VALUEat all. But I doubt that the questioner will ever read these comments, as after five years of absence, coming back is quiet unlikely.