18

Is there any operator or trick for such operation? Or is it necessary to use

if(5<i && i<10)

?

Whimusical
  • 6,401
  • 11
  • 62
  • 105

6 Answers6

24

You cannot chain inequalities. You can, however, define a static boolean method isInRange(value, low, high) that will perform such a check.

Some other languages, like Python or Icon, allow this notation.

Gyscos
  • 1,772
  • 17
  • 22
  • 12
    Perhaps the parameters should be ordered as `isInRange(low, value, high)` e.g. `isInRange(5, i, 10)`. – Salman A May 18 '12 at 19:07
13

There is no such thing in Java (unless you work with booleans).

The 5<iresults in a boolean on the left side on <10 which the compiler dislikes.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
5

I'm afraid chained inequalities are unsupported in Java at this time. Check this post for languages which do.

Community
  • 1
  • 1
danielmhanover
  • 3,094
  • 4
  • 35
  • 51
5

You can use a single comparison but is more complicated than its worth usually.

if (i - (Integer.MIN_VALUE + 6) < Integer.MIN_VALUE + (10 - 6))

This uses underflow to adjust all the value 5 and below to be a large positive value.

The only reason you would use this is as a micro-optimisation.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

Range

Comparisons cannot be chained in Java.

The standard way for doing a range check is to use either Guava Ranges:

import com.google.common.collect.Range;
...
    if(Range.open(5, 10).contains(x)){

or Apache Commons Lang (it provides only closed ranges, though):

import org.apache.commons.lang3.Range;
...
    if(Range.between(5 + 1, 10 - 1).contains(x)){
jihor
  • 2,478
  • 14
  • 28
1

a < x < b is equivalent to (x-a)(x-b)<0, or if x is an expression you only wanna calculate once,

(x - (a+b)/2) ^ 2 < (b-a)^2 / 4

Same deal with two nonstrict equalities. I don't think there's a way to deal with one strict and one nonstrict equality, however (unless x is an integer).

H.v.M.
  • 1,348
  • 3
  • 16
  • 42