111

Hoping for something more elegant than

if (i>0 && i<100) 
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
herpderp
  • 15,819
  • 12
  • 42
  • 45

22 Answers22

256

You could add spacing ;)

if (i > 0 && i < 100) 
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
  • 13
    don't cramp my style! no i usually space it like that. – herpderp Apr 06 '11 at 23:34
  • 22
    On suggestion is that since we'd typically write something like "0 < i < 100", it's nice to follow that as much as possible to make the code a bit easier to read: `0 < i && i < 100`. It's a little bit weird to have the constant on the left in `0 < i`, but I think it's worth it to have the overall expression that looks most like `0 < ... < 100`. – Joshua Taylor Nov 04 '15 at 21:24
62

For those using commons lang an option is to use Range:

Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
    // do something
}

Also see: how to construct a apache commons 3.1 Range<Integer> object

Community
  • 1
  • 1
beat
  • 1,857
  • 1
  • 22
  • 36
38

I think

if (0 < i && i < 100) 

is more elegant. Looks like maths equation.

If you are looking for something special you can try:

Math.max(0, i) == Math.min(i, 100)

at least it uses library.

Vitaly
  • 2,552
  • 2
  • 18
  • 21
  • 13
    Note that the 2nd solution is inclusive, 1st is not. – holmis83 Jul 03 '18 at 15:01
  • Shouldn't it be `Math.min(i, 99)`? Because if I enter `100` it will still return true. I think `Math.max(0, i) == Math.min(i, 100)` works for `0 < i <= 100` – Irshu Jan 15 '19 at 04:54
  • @Irshu Not quite - because if `i = 0` then `Math.max(0, i) == Math.min(i, 99)` still evaluates to `0 == 0` – domids Jan 28 '21 at 09:05
20
ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);
  • it returns true if minValue <= x <= MaxValue - i.e. within the range
  • it returns false if x < minValue or x > maxValue - i.e. out of range

Use with if condition as shown below:

int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
    System.out.println("Value is with in the Range.");
} else {
    System.out.println("Value is out of the Range.");
}

The below program checks, if any of the passed integer value in the hasTeen method is within the range of 13 (inclusive) to 19 (inclusive).


import java.time.temporal.ValueRange;
  
public class TeenNumberChecker {

    public static void main(String[] args) {
        System.out.println(hasTeen(9, 99, 19));
        System.out.println(hasTeen(23, 15, 42));
        System.out.println(hasTeen(22, 23, 34));
    }

    public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {

        ValueRange range = ValueRange.of(13, 19);
        System.out.println("*********Int validation Start ***********");
        System.out.println(range.isIntValue());
        System.out.println(range.isValidIntValue(firstNumber));
        System.out.println(range.isValidIntValue(secondNumber));
        System.out.println(range.isValidIntValue(thirdNumber));
        System.out.println(range.isValidValue(thirdNumber));
        System.out.println("**********Int validation End**************");

        if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
            return true;
        } else
            return false;
    }
}

OUTPUT

true as 19 is part of range

true as 15 is part of range

false as all three value passed out of range

informatik01
  • 16,038
  • 10
  • 74
  • 104
Arpan Saini
  • 4,623
  • 1
  • 42
  • 50
  • Nice, I have used it in if condition like - `if(ValueRange.of(90, 100).isValidIntValue(91)) { "Value is in range." }` – Yash Apr 21 '19 at 05:18
  • **NOTE:** actually the class `ValueRange` is not *directly* meant for pure integer comparison, but rather for (quote from the [JavaDocs](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/ValueRange.html), emphasis mine): "The range of valid values for a **date-time** field." – informatik01 Jun 16 '21 at 23:30
13

I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all && cases.

So, you can use any of the below approach to avoid writing extra unit tests.

Using Java 8 Streams:

if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))

Using Math class:

if(Math.max(0, i) == Math.min(i, 100))

Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.

Sahil Chhabra
  • 10,621
  • 4
  • 63
  • 62
  • You have to write all the unit tests nontheless. The difference is that it's probably not noted by code checking tools. – kap Feb 14 '21 at 22:13
  • @kap Obviously one should write all valid unit tests. But, the approach used in OP will require a test case which is practically impossible to cover i.e. false && false. That’s why I mentioned a way to avoid covering this invalid extra test case. – Sahil Chhabra Feb 15 '21 at 14:20
  • The Streams solution is awesomely bad. Consider a bigger range of -2.000.000.000 and 2.000.000.000. Creating a list of four billion entries, just to check if one value is in it, is simply madness. – Sven Döring Feb 28 '23 at 19:24
  • @SvenDöring Obviously its not a good option for bigger range and I had already mentioned it in my last line of the answer. Also, please note that this answer is for the range mentioned in the question i.e. 0 - 100 – Sahil Chhabra Mar 01 '23 at 23:23
8

I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.

class MathUtil
{
   public static boolean betweenExclusive(int x, int min, int max)
   {
       return x>min && x<max;    
   }
}

This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..

mdma
  • 56,943
  • 12
  • 94
  • 128
  • 9
    It is a good idea, until someone puts in `boolean accepted = MathUtil.betweenExclusive(min,max,x);` and mungles the order. :( – corsiKa Apr 06 '11 at 23:16
  • I know! Ouch. In those cases, a Range object can be useful. – mdma Apr 06 '11 at 23:18
  • My RangeChecker object was actually a joke, but in hindsight, it actually isn't that bad of a solution (even if it is overkill.) – corsiKa Apr 06 '11 at 23:20
  • It would be better if it were a method directly defined in `Integer` class. There is zero confusion when you do; `myNum.isBetween(min, max)` – buræquete Feb 17 '16 at 07:00
  • Simple example: I have list of people with their ages, and want to check, if each of them is old aged, middle aged, child or toddler. I can have named ranges of ages, and then my code is quite readable. Or I can have lots of > and < and my code is gibberish. – Mikhail Batcer Aug 17 '17 at 16:43
6

If you're looking for something more original than

if (i > 0 && i < 100)

you can try this

import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))
esin88
  • 3,091
  • 30
  • 35
4

This guy made a nice Range class.

Its use however will not yield nice code as it's a generic class. You'd have to type something like:

if (new Range<Integer>(0, 100).contains(i))

or (somewhat better if you implement first):

class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))

Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.

Community
  • 1
  • 1
velis
  • 8,747
  • 4
  • 44
  • 64
4

Google's Java Library Guava also implements Range:

import com.google.common.collect.Range;

Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false

Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true

Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true
p13rr0m
  • 1,107
  • 9
  • 21
3
if ( 0 < i && i < 100)  

if ( 'a' <= c && c <= 'z' )
irreputable
  • 44,725
  • 9
  • 65
  • 93
1

Use this code :

if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)
Vishal Tathe
  • 180
  • 1
  • 8
1

if you are using Spring data you can also use the Range object from Spring.

range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.
Maurice
  • 6,698
  • 9
  • 47
  • 104
1

That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.

Borealid
  • 95,191
  • 9
  • 106
  • 122
  • Trying to be clever with subtraction can lead to integer over- or underflow and give you an incorrect result. – corsiKa Apr 06 '11 at 23:19
1

Just my 2 cts

    // Exclusive    
    public boolean isOrdered(int n1, int n2, int n3) {
        return n1 < n2 && n2 < n3 ;
    }

call it like to see it is one of 1 to 99

    if (isOrdered(0,i,100)) 
mcvkr
  • 3,209
  • 6
  • 38
  • 63
0

Try:

if (i>0 && i<100) {} 

it will work at least ;)

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
Endi
  • 40
  • 2
0
if (i in 0..100) {}

please try this for efficient code ;)

Vanya Rachel
  • 1,329
  • 1
  • 18
  • 20
0

If you just want to test whether the value of i is in the range [0..100), and you want the boolean result, then

i >= 0 && i < 100

is fine and will give you true or false. If you are willing to throw an exception if the value is out of range, you can use the built-in checkIndex method

Objects.checkIndex(i, 100)

which will throw IndexOutOfBoundsException if out of range. Granted, it is not a general solution, and is really only prettier if your context is one in which your range check is being done for checking array bounds, but it has the advantage of not needed any third party libraries, which is nice for small programs.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
0

Try this if strategy. Seems solid.

int num = 5;
    
    //random values; can be changed
    int a = 3;
    int b = 7;
    
    if (num >= 3 && num <= 7) {
        //Your Code Here
    }
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32190536) – Japhei Jul 10 '22 at 10:34
0

Wrote this program to check the value of 3 integer parameters against a range.

I have created a separate method to check the range of the each value using if/else-if statements.

I hope this helps someone.

public class TeenNumberChecker {

    public static void main(String[] args) {
        
        boolean isTeen = hasTeen();

    }

    public static boolean hasTeen(int valueOne, int valueTwo, int valueThree) {
        
        
        if (valueOne > 13 && valueOne < 19) {
            
            return true;
            
        } else if (valueTwo > 13 && valueTwo < 19) {
            
            return true;
            
        } else if (valueThree > 13 && valueThree < 19) {
            
            return true;
            
        }else {
            
            return false;
            
        }

    }
}
SasithM
  • 39
  • 2
-1

if(i <= 0 || i >=100)

It will work.

-1

If you are confident that numbers are stored in 2's complement form:

return  ((x-low) <= (high-low));

A more general and safer solution would be:

return ((x-high)*(x-low) <= 0);
Guru
  • 2,739
  • 1
  • 25
  • 27
-1
 Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
    if(timeRange.contains(systemtime)){
        Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
    }
VIVEK CHOUDHARY
  • 468
  • 5
  • 8