by BehindJava

How to Check if a variable is between two numbers with Java

Home » interview » How to Check if a variable is between two numbers with Java

In this blog, we are going to learn about Checking if a variable is between two numbers with Java.

In the below example, we have a program where we want to find weather a user is a senior citizen or not for this we will be writing a logic using && operator to find the range between to numbers.

public class BehindJava {

	public static void main(String[] args) {
		int a = 20;
		if (a != 0 && a > 1 && a < 60) {
			System.out.println("User is not a Senior Citizen");
		} else {
			System.out.println("User is a Senior Citizen");
		}
	}
}

Output:

User is not a Senior Citizen

using org.apache.commons.lang3.Range is a nice solution for this. It can also integrate nicely with Guava Preconditions for argument checking. Some example code showing usage is

import java.util.List;
import org.apache.commons.lang3.Range;

public class BehindJava {

	public static void main(String[] args) {
		// Create a range object
		Range<Double> validRange = Range.between(90.0, 180.0);
		// and some test values
		List<Double> testValues = List.of(65.3, 89.99, 90.0, 90.11, 134.4, 177.7, 180.00, 180.000001, 32321.884);
		// Test them all
		for (Double testValue : testValues) {
			// Check if it's in the range
			final boolean inRange = validRange.contains(testValue);
			System.out.println(String.format("[%f] in range [%b]", testValue, inRange));
		}
	}
}

Output:

[65.300000] in range [false]
[89.990000] in range [false]
[90.000000] in range [true]
[90.110000] in range [true]
[134.400000] in range [true]
[177.700000] in range [true]
[180.000000] in range [true]
[180.000001] in range [false]
[32321.884000] in range [false]

Using a static method can be a benefit in terms of readability and it could also lead to better performance. In java.lang.Math you have a method isBetween(int toCheck, int from, int to), which is defined as

public static boolean isBetween(int toCheck, int from, int to){

  // eventually validate the range
  return from <= toCheck && toCheck <= to;
}

Finally, validate the range by returning from = toCheck && toCheck = to; using the public static boolean isBetween(int toCheck, int from, int to) function.

Importing static Math.isBetween allows you to write code like this, which is the first advantage.

if(isBetween(userInput, 0, 16)){
  //...
}

The second advantage is that repeatedly using this method (for boundary checks, for instance, in Strings, arrays, or other statically-sized data structures) can result in an easily C2-compiled method (likely inlined). Eventually, if someone points out that the HotSpot compiler generates a branch because there is a conditional jump, then can write an improvement that generates branchless code, and each application of this method c.