Java ProgramsControl FlowCheck Number Within Range

Check Number Within Range in Java

beginner·  Control Flow  ·  Conditional Statements

Problem

A number falls within a range when it's neither smaller than the lower bound nor larger than the upper bound, with both ends counted as valid.

Given a number and a lower and upper bound, determine whether the number falls within that range.

Input
45, 1 to 100
Output
45 is within range: true

Java Program

Java
public class NumberWithinRange { public static void main(String[] args) { int n = 45; int low = 1, high = 100; boolean withinRange = (n >= low && n <= high); // inclusive on both ends System.out.println(n + " is within range: " + withinRange); } }

Output

45 is within range: true

Core Logic

Combining two comparisons with a logical AND checks both boundary conditions in a single expression.

How It Works
  1. 1n >= low confirms the number isn't smaller than the lower bound.
  2. 2n <= high confirms the number isn't larger than the upper bound.
  3. 3Both conditions must hold together, joined by &&, for the number to count as within range.
For n = 45 with bounds 1 and 100, both comparisons hold, so withinRange is true.
💡

Key Point: Using >= and <= rather than > and < makes both boundary values themselves count as within range — an exclusive range would need strict inequalities instead.

Key Concepts

logical ANDcomparison operators

Related Programs