How to Check If a Number Is Within a Specific Range in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number falls within a specific range in Java. We will cover the fundamental concepts of defining a numerical range using lower and upper bounds, utilizing logical operators to perform the range check, and understanding how to include boundary values in your range comparisons. Through hands-on exercises, you will gain practical experience in implementing these techniques in Java code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/booleans("Booleans") java/BasicSyntaxGroup -.-> java/if_else("If...Else") subgraph Lab Skills java/data_types -.-> lab-559970{{"How to Check If a Number Is Within a Specific Range in Java"}} java/operators -.-> lab-559970{{"How to Check If a Number Is Within a Specific Range in Java"}} java/booleans -.-> lab-559970{{"How to Check If a Number Is Within a Specific Range in Java"}} java/if_else -.-> lab-559970{{"How to Check If a Number Is Within a Specific Range in Java"}} end

Define Range with Lower and Upper Bounds

In this step, we will learn how to define a numerical range using lower and upper bounds in Java. Understanding how to work with ranges is a fundamental concept in programming, allowing us to check if a value falls within a specific set of numbers.

A range is simply a set of numbers between a starting point (the lower bound) and an ending point (the upper bound). For example, the range between 1 and 10 includes all numbers from 1 up to 10.

Let's create a simple Java program to define and work with a range.

  1. Open the HelloJava.java file in the WebIDE editor if it's not already open. We will modify this file for our new program.

  2. Replace the entire contents of the file with the following code:

    public class HelloJava {
        public static void main(String[] args) {
            // Define the lower and upper bounds of the range
            int lowerBound = 10;
            int upperBound = 50;
    
            // Print the defined range
            System.out.println("Defined Range: [" + lowerBound + ", " + upperBound + "]");
        }
    }

    Let's look at the new parts of this code:

    • int lowerBound = 10;: This line declares an integer variable named lowerBound and assigns it the value 10. This is our starting point for the range.
    • int upperBound = 50;: This line declares an integer variable named upperBound and assigns it the value 50. This is our ending point for the range.
    • System.out.println("Defined Range: [" + lowerBound + ", " + upperBound + "]");: This line prints a message to the console showing the defined range using the values of lowerBound and upperBound. The + symbol is used to combine text strings and variable values.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Now, let's compile our modified program. Open the Terminal at the bottom of the WebIDE and make sure you are in the ~/project directory. Then, run the following command:

    javac HelloJava.java

    If there are no errors, the compilation was successful.

  5. Finally, let's run the program to see the output. In the Terminal, run:

    java HelloJava

    You should see the following output:

    Defined Range: [10, 50]

    This confirms that our program correctly defined and printed the lower and upper bounds of the range.

In the next step, we will learn how to check if a number falls within this defined range using logical operators.

Use Logical Operators for Range Check

In this step, we will learn how to use logical operators in Java to check if a number falls within the range we defined in the previous step. Logical operators are used to combine or modify boolean expressions (expressions that are either true or false).

To check if a number is within a range defined by a lower bound and an upper bound, we need to check two conditions:

  1. Is the number greater than or equal to the lower bound?
  2. Is the number less than or equal to the upper bound?

Both of these conditions must be true for the number to be within the range. In Java, we use the logical AND operator (&&) to combine these two conditions.

Let's modify our HelloJava.java program to include this range check.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. Modify the main method to include a variable for the number to check and the range check logic. Replace the existing main method content with the following:

        public static void main(String[] args) {
            // Define the lower and upper bounds of the range
            int lowerBound = 10;
            int upperBound = 50;
    
            // Define the number to check
            int numberToCheck = 35;
    
            // Check if the number is within the range using logical operators
            boolean isInRange = (numberToCheck >= lowerBound) && (numberToCheck <= upperBound);
    
            // Print the result
            System.out.println("Defined Range: [" + lowerBound + ", " + upperBound + "]");
            System.out.println("Number to Check: " + numberToCheck);
            System.out.println("Is " + numberToCheck + " within the range? " + isInRange);
        }

    Here's what we added:

    • int numberToCheck = 35;: This line declares an integer variable numberToCheck and assigns it the value 35. This is the number we want to check against our range.
    • boolean isInRange = (numberToCheck >= lowerBound) && (numberToCheck <= upperBound);: This is the core of our range check.
      • numberToCheck >= lowerBound: This checks if numberToCheck is greater than or equal to lowerBound.
      • numberToCheck <= upperBound: This checks if numberToCheck is less than or equal to upperBound.
      • &&: This is the logical AND operator. It returns true only if both the condition on its left and the condition on its right are true.
      • The result of this entire expression (true or false) is stored in a boolean variable named isInRange.
    • The System.out.println lines now also print the number being checked and the result of the range check.
  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Defined Range: [10, 50]
    Number to Check: 35
    Is 35 within the range? true

    Since 35 is indeed between 10 and 50 (inclusive), the program correctly outputs true.

Try changing the value of numberToCheck to something outside the range (e.g., 5 or 60) and re-compile and re-run the program to see how the output changes.

Include Boundary Values in Range

In the previous step, we used the >= (greater than or equal to) and <= (less than or equal to) operators to check if a number is within a range. These operators are crucial because they include the boundary values (the lower and upper bounds) in the range check.

For example, if our range is [10, 50], a number is considered within the range if it is 10, 50, or any number between 10 and 50. If we had used > (greater than) and < (less than) instead, the range would be (10, 50), which means 10 and 50 themselves would not be included.

Let's confirm this behavior by testing our program with the boundary values.

  1. Open the HelloJava.java file in the WebIDE editor.

  2. We will test the range check with the lower bound and the upper bound. Modify the main method to test both lowerBound and upperBound as the numberToCheck.

    public class HelloJava {
        public static void main(String[] args) {
            // Define the lower and upper bounds of the range
            int lowerBound = 10;
            int upperBound = 50;
    
            // Test with the lower bound
            int numberToCheck1 = lowerBound;
            boolean isInRange1 = (numberToCheck1 >= lowerBound) && (numberToCheck1 <= upperBound);
            System.out.println("Defined Range: [" + lowerBound + ", " + upperBound + "]");
            System.out.println("Number to Check: " + numberToCheck1);
            System.out.println("Is " + numberToCheck1 + " within the range? " + isInRange1);
            System.out.println("---"); // Separator for clarity
    
            // Test with the upper bound
            int numberToCheck2 = upperBound;
            boolean isInRange2 = (numberToCheck2 >= lowerBound) && (numberToCheck2 <= upperBound);
            System.out.println("Number to Check: " + numberToCheck2);
            System.out.println("Is " + numberToCheck2 + " within the range? " + isInRange2);
        }
    }

    We've added a second test case using numberToCheck2 set to upperBound.

  3. Save the file (Ctrl+S or Cmd+S).

  4. Compile the modified program in the Terminal:

    javac HelloJava.java
  5. Run the compiled program:

    java HelloJava

    You should see output similar to this:

    Defined Range: [10, 50]
    Number to Check: 10
    Is 10 within the range? true
    ---
    Number to Check: 50
    Is 50 within the range? true

    As you can see, both 10 (the lower bound) and 50 (the upper bound) are correctly identified as being within the range because we used the >= and <= operators. This confirms that our range check includes the boundary values.

Understanding whether a range includes its boundaries (inclusive) or excludes them (exclusive) is important when defining conditions in your programs. The >= and <= operators create an inclusive range.

Summary

In this lab, we learned how to define a numerical range in Java by setting lower and upper bounds using integer variables. We modified a simple Java program to declare these bounds and print the defined range to the console, understanding how to combine text and variable values for output. This foundational step is crucial for subsequently checking if a number falls within this specified range.