Ranges
suggest changeJava has no range literal like Kotlin's 1..10 or Python's range(10), and no Range class in the standard library. Ranges still come up all the time, and the JDK handles them in several places:
- the classic
forloop IntStream.rangeandrangeClosed(and thelongversions)- methods that take a start and end index:
substring,subList,Arrays.copyOfRange,Arrays.fill - range and index checks:
Math.clamp,Objects.checkIndex - range views of sorted collections:
subSet,headMap,floorEntry - date ranges with
LocalDate.datesUntil
This article covers each of these, then shows how to write a small Range record and when to use Guava's Range, RangeSet and RangeMap.
The examples are single files you run with java Example.java. Output is from JDK 25.
Related articles: For Loops, Using IntStream to iterate over indexes, Streams of Primitives and TreeMap and TreeSet.
Half-open vs. closed
There are two ways to describe the range of numbers from 0 to 4:
- half-open
[0, 5): the start is included and the end is excluded - closed
[0, 4]: both ends are included
Almost every JDK API uses half-open ranges. substring(begin, end), subList(from, to), IntStream.range(start, end) and Arrays.copyOfRange(a, from, to) all exclude the end. Half-open ranges have useful properties:
- the length is
end - start, with no+ 1 [0, n)covers exactly the valid indexes of an array or list of lengthn- an empty range is
[x, x), which needs no special case - adjacent ranges such as
[0, 5)and[5, 10)meet without overlapping or leaving a gap
Use closed ranges when the end value means something to people, like "pages 1 to 10" or "ages 18 to 65".
The for loop
The for loop is the most common way to go over a range:
public class ForRange {
public static void main(String[] args) {
// 0 to 4: half-open, end excluded
for (int i = 0; i < 5; i++) System.out.print(i + " ");
System.out.println();
// 1 to 5: closed, end included
for (int i = 1; i <= 5; i++) System.out.print(i + " ");
System.out.println();
// step of 3
for (int i = 0; i < 20; i += 3) System.out.print(i + " ");
System.out.println();
// counting down from 10 to 1
for (int i = 10; i >= 1; i--) System.out.print(i + " ");
System.out.println();
// a range of chars
for (char c = 'a'; c <= 'f'; c++) System.out.print(c);
System.out.println();
}
}
0 1 2 3 4
1 2 3 4 5
0 3 6 9 12 15 18
10 9 8 7 6 5 4 3 2 1
abcdef
i < 5 gives a half-open range and i <= 5 a closed one. Changing the update expression gives you any step, or counts down.
Overflow at the end of the type
A closed loop that ends at the largest value of its type never finishes. When i is Integer.MAX_VALUE, i++ wraps around to Integer.MIN_VALUE, and i <= Integer.MAX_VALUE is still true:
import java.util.stream.IntStream;
public class Overflow {
public static void main(String[] args) {
int n = 0;
for (int i = Integer.MAX_VALUE - 2; i <= Integer.MAX_VALUE; i++) {
if (++n > 5) {
System.out.println("still looping, i = " + i);
break;
}
}
IntStream.rangeClosed(Integer.MAX_VALUE - 2, Integer.MAX_VALUE)
.forEach(System.out::println);
}
}
still looping, i = -2147483646
2147483645
2147483646
2147483647
IntStream.rangeClosed handles the edge correctly. The same trap exists with byte (b <= 127) and char loops.
Don't step through doubles
A loop that adds 0.1 to a double accumulates rounding error, so the number of iterations and the last value are not what you expect:
public class DoubleLoop {
public static void main(String[] args) {
int n = 0;
double last = 0;
for (double x = 0; x <= 1.0; x += 0.1) {
n++;
last = x;
}
System.out.println(n + " iterations, last x = " + last);
n = 0;
for (int i = 0; i <= 10; i++) {
last = i / 10.0;
n++;
}
System.out.println(n + " iterations, last x = " + last);
}
}
11 iterations, last x = 0.9999999999999999
11 iterations, last x = 1.0
The first loop never reaches 1.0. Loop over integers and compute each double from the counter, so every value has only one rounding error. See Floating Point Operations for more.
IntStream.range and rangeClosed
IntStream.range(start, end) is a stream of the ints in [start, end), and IntStream.rangeClosed(start, end) the ints in [start, end]:
import java.util.List;
import java.util.stream.IntStream;
public class IntRange {
public static void main(String[] args) {
IntStream.range(0, 5).forEach(i -> System.out.print(i + " "));
System.out.println();
IntStream.rangeClosed(1, 5).forEach(i -> System.out.print(i + " "));
System.out.println();
System.out.println("sum 1..100 = " + IntStream.rangeClosed(1, 100).sum());
System.out.println("count = " + IntStream.range(10, 20).count());
System.out.println("empty: " + IntStream.range(5, 5).count()
+ " " + IntStream.range(5, 1).count());
int[] squares = IntStream.rangeClosed(1, 6).map(i -> i * i).toArray();
System.out.println(java.util.Arrays.toString(squares));
List<Integer> evens = IntStream.range(0, 10).filter(i -> i % 2 == 0)
.boxed().toList();
System.out.println(evens);
}
}
0 1 2 3 4
1 2 3 4 5
sum 1..100 = 5050
count = 10
empty: 0 0
[1, 4, 9, 16, 25, 36]
[0, 2, 4, 6, 8]
When start >= end (or start > end for rangeClosed) the stream is empty. There is no exception and the range doesn't count down.
A range stream is a primitive IntStream, so sum(), average() and max() work directly with no boxing. Call boxed() when you need a Stream<Integer>, for example to collect into a List. count() on a range doesn't iterate: the stream knows its size.
Use a range to work with indexes inside a stream pipeline, for example to pair names[i] with i. When you only need the elements, a for-each loop over the array or list is simpler. When the body has side effects or uses break, a plain for loop is easier to read than forEach.
Steps and descending ranges
range has no step argument. There are two ways to get one:
import java.util.Arrays;
import java.util.stream.IntStream;
public class StepRange {
public static void main(String[] args) {
// step: iterate(seed, hasNext, next) (Java 9+)
int[] byThree = IntStream.iterate(0, i -> i < 20, i -> i + 3).toArray();
System.out.println(Arrays.toString(byThree));
// step via map: 0, 5, 10, ... 50
int[] byFive = IntStream.rangeClosed(0, 10).map(i -> i * 5).toArray();
System.out.println(Arrays.toString(byFive));
// descending: 10 down to 1
int[] down = IntStream.iterate(10, i -> i >= 1, i -> i - 1).toArray();
System.out.println(Arrays.toString(down));
// descending via map over an ascending range
int from = 1, to = 5;
int[] down2 = IntStream.rangeClosed(from, to).map(i -> to - i + from).toArray();
System.out.println(Arrays.toString(down2));
}
}
[0, 3, 6, 9, 12, 15, 18]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
IntStream.iterate(seed, hasNext, next)(Java 9) works like aforloop: start value, condition, update. It can step by any amount in either direction.mapover a plain range (i * 5, orto - i + fromto reverse) keeps the stream sized and splits well for parallel streams.
long, char and double ranges
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class OtherTypes {
public static void main(String[] args) {
// long ranges go past Integer.MAX_VALUE
System.out.println(LongStream.rangeClosed(1, 3_000_000_000L).count());
System.out.println(LongStream.rangeClosed(1, 20).reduce(1, (a, b) -> a * b));
// characters are ints underneath
String letters = IntStream.rangeClosed('a', 'z')
.mapToObj(Character::toString)
.collect(Collectors.joining());
System.out.println(letters);
// doubles: derive each value from an int counter
String xs = IntStream.rangeClosed(0, 10)
.mapToObj(i -> String.valueOf(i / 10.0))
.collect(Collectors.joining(" "));
System.out.println(xs);
}
}
3000000000
2432902008176640000
abcdefghijklmnopqrstuvwxyz
0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
LongStream.rangeandrangeClosedtakelongbounds, for ranges that go pastInteger.MAX_VALUE.- A
charis a number, soIntStream.rangeClosed('a', 'z')gives the code points of the letters.Character.toString(int)turns each one back into a string. DoubleStreamhas norange. Map an int range to doubles, as in the loop example above.
Index ranges in the JDK
Many JDK methods take a pair of indexes. They all use half-open [from, to):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HalfOpen {
public static void main(String[] args) {
String s = "Hello, World";
System.out.println(s.substring(7, 12)); // [7, 12)
System.out.println(s.indexOf('o', 5)); // search from 5
System.out.println(s.indexOf('o', 5, 8)); // search in [5, 8) (Java 21)
int[] a = {10, 20, 30, 40, 50, 60};
System.out.println(Arrays.toString(Arrays.copyOfRange(a, 1, 4)));
System.out.println(Arrays.stream(a, 2, 5).sum());
int[] zeros = new int[8];
Arrays.fill(zeros, 2, 5, 7);
System.out.println(Arrays.toString(zeros));
int[] sorted = {1, 3, 5, 7, 9, 11};
System.out.println(Arrays.binarySearch(sorted, 0, 3, 5));
List<String> list = new ArrayList<>(List.of("a", "b", "c", "d", "e", "f"));
List<String> middle = list.subList(1, 4);
System.out.println(middle);
middle.clear(); // removes b, c, d from list
System.out.println(list);
StringBuilder sb = new StringBuilder("0123456789");
sb.delete(3, 7);
System.out.println(sb);
}
}
World
8
-1
[20, 30, 40]
120
[0, 0, 7, 7, 7, 0, 0, 0]
2
[b, c, d]
[a, e, f]
012789
String.substring(begin, end),StringBuilder.delete(start, end)andString.indexOf(ch, from, to)(Java 21) work on part of a string.Arrays.copyOfRange,Arrays.fill,Arrays.sort,Arrays.binarySearchandArrays.streamall have overloads that take a range, so you don't need to copy part of an array first.List.subList(from, to)returns a view, not a copy. Changes to the view write through to the list, solist.subList(1, 4).clear()is the easiest way to remove a range of elements. Don't keep a sublist around after changing the original list's size outside the view: its next use throwsConcurrentModificationException. Wrap it innew ArrayList<>(...)or callList.copyOfif you need an independent copy.
Passing an index outside [0, length] throws IndexOutOfBoundsException (StringIndexOutOfBoundsException for strings, ArrayIndexOutOfBoundsException for some array methods).
Checking whether a value is in a range
There is no between operator. Write two comparisons:
import java.util.Objects;
public class Checks {
static boolean inRange(int x, int lo, int hi) { // closed [lo, hi]
return x >= lo && x <= hi;
}
public static void main(String[] args) {
System.out.println(inRange(5, 1, 10) + " " + inRange(11, 1, 10));
// Math.clamp (Java 21) forces a value into [min, max]
System.out.println(Math.clamp(150, 0, 100));
System.out.println(Math.clamp(-5, 0, 100));
System.out.println(Math.clamp(0.75, 0.0, 1.0));
// index checks: return the index or throw IndexOutOfBoundsException
System.out.println(Objects.checkIndex(3, 10));
System.out.println(Objects.checkFromToIndex(2, 5, 10));
System.out.println(Objects.checkFromIndexSize(2, 5, 10));
try {
Objects.checkFromToIndex(4, 12, 10);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
try {
Objects.checkIndex(10, 10);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
}
true false
100
0
0.75
3
2
2
Range [4, 12) out of bounds for length 10
Index 10 out of bounds for length 10
- Writing
x >= lo && x <= hiwith the variable in the middle of each comparison makes the bounds easy to read and check. Math.clamp(value, min, max)(Java 21) returnsvaluelimited to[min, max]. It has overloads forint,long,floatanddouble, and throwsIllegalArgumentExceptionifmin > max.Objects.checkIndex,checkFromToIndexandcheckFromIndexSizevalidate an index or a sub-range against a length, and return the start index when it's valid. They throwIndexOutOfBoundsExceptionwith a clear message, and the JIT optimizes them well. Use them when your own methods take index arguments.
Ranges in sorted collections
TreeSet and TreeMap implement NavigableSet and NavigableMap, which can return the part of the collection between two keys:
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeMap;
import java.util.TreeSet;
public class Sorted {
public static void main(String[] args) {
NavigableSet<Integer> nums = new TreeSet<>(List.of(1, 4, 9, 16, 25, 36, 49, 64, 81, 100));
System.out.println(nums.subSet(16, 49)); // [16, 49)
System.out.println(nums.subSet(16, true, 49, true)); // [16, 49]
System.out.println(nums.headSet(9)); // < 9
System.out.println(nums.tailSet(64)); // >= 64
System.out.println(nums.subSet(10, true, 50, false).descendingSet());
TreeMap<String, Integer> stock = new TreeMap<>();
for (String w : List.of("apple", "banana", "blueberry", "cherry", "date", "fig")) {
stock.put(w, w.length());
}
// all keys starting with "b": the range ["b", "c")
System.out.println(stock.subMap("b", "c"));
System.out.println(stock.headMap("c", false).keySet());
// views are live: adding to the set shows up in the view
NavigableSet<Integer> view = nums.subSet(10, true, 50, false);
nums.add(30);
System.out.println(view);
try {
view.add(70);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
[16, 25, 36]
[16, 25, 36, 49]
[1, 4]
[64, 81, 100]
[49, 36, 25, 16]
{banana=6, blueberry=9}
[apple, banana, blueberry]
[16, 25, 30, 36, 49]
key out of range
subSet(from, to),headSet(to)andtailSet(from)are half-open by default. The overloads withbooleanflags let you include or exclude each end.- Strings sort lexicographically, so
subMap("b", "c")returns every key starting withb. - The results are live views backed by the original collection, so they are cheap to create, even for a big tree. Adding a key outside the view's range through the view throws
IllegalArgumentException. - The two-argument
subSetreturns aSortedSet. Use the four-argument version when you need aNavigableSet(fordescendingSet()and similar).
A TreeMap also works as a lookup table for ranges. Store the lower bound of each range as a key, and floorEntry(x) finds the range that x falls into:
import java.util.TreeMap;
public class Buckets {
// each key is the lower bound of a range that extends to the next key
static final TreeMap<Integer, String> GRADES = new TreeMap<>();
static {
GRADES.put(0, "F");
GRADES.put(60, "D");
GRADES.put(70, "C");
GRADES.put(80, "B");
GRADES.put(90, "A");
}
static String grade(int score) {
return GRADES.floorEntry(score).getValue();
}
public static void main(String[] args) {
for (int s : new int[] {45, 60, 79, 80, 99}) {
System.out.print(s + "=" + grade(s) + " ");
}
System.out.println();
}
}
45=F 60=D 79=C 80=B 99=A
Each lookup is O(log n), and adding a range is one put. floorEntry returns null for a value below the lowest key (a negative score here), so either start the map at the smallest possible value or check for null.
Date ranges
LocalDate.datesUntil(end) (Java 9) is a stream of the dates in [start, end). Pass a Period to step by weeks or months:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.stream.Collectors;
public class Dates {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2026, 2, 26);
LocalDate end = LocalDate.of(2026, 3, 3);
// datesUntil is half-open: end is excluded
System.out.println(start.datesUntil(end)
.map(LocalDate::toString).collect(Collectors.joining(" ")));
// include the end date
System.out.println(start.datesUntil(end.plusDays(1)).count() + " days inclusive");
// with a step: every Monday in March 2026
LocalDate firstMonday = LocalDate.of(2026, 3, 2);
System.out.println(firstMonday.datesUntil(LocalDate.of(2026, 4, 1), Period.ofWeeks(1))
.map(d -> String.valueOf(d.getDayOfMonth())).collect(Collectors.joining(", ")));
System.out.println(ChronoUnit.DAYS.between(start, end) + " days between");
// is a date / time inside a range?
LocalDate d = LocalDate.of(2026, 3, 1);
System.out.println(!d.isBefore(start) && d.isBefore(end));
LocalTime open = LocalTime.of(9, 0), close = LocalTime.of(17, 30);
LocalTime now = LocalTime.of(17, 30);
System.out.println(!now.isBefore(open) && now.isBefore(close));
}
}
2026-02-26 2026-02-27 2026-02-28 2026-03-01 2026-03-02
6 days inclusive
2, 9, 16, 23, 30
5 days between
true
false
For checks on dates and times, !d.isBefore(start) && d.isBefore(end) is the half-open start <= d < end. Half-open ranges fit time well: a shop open [09:00, 17:30) is closed at exactly 17:30, and consecutive time slots don't overlap. See Dates and Time using java.time for more on java.time.
Writing a Range record
If ranges are part of your domain (reservations, pages, version numbers), a small record keeps the logic in one place:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.stream.IntStream;
// a half-open range of ints: [start, end)
record Range(int start, int end) implements Iterable<Integer> {
Range {
if (start > end) {
throw new IllegalArgumentException("start " + start + " > end " + end);
}
}
static Range closed(int first, int last) {
return new Range(first, Math.addExact(last, 1));
}
int length() { return end - start; }
boolean isEmpty() { return start == end; }
boolean contains(int x) { return x >= start && x < end; }
boolean contains(Range r) { return r.start >= start && r.end <= end; }
boolean overlaps(Range r) { return start < r.end && r.start < end; }
Optional<Range> intersection(Range r) {
int s = Math.max(start, r.start), e = Math.min(end, r.end);
return s < e ? Optional.of(new Range(s, e)) : Optional.empty();
}
IntStream stream() { return IntStream.range(start, end); }
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
int next = start;
public boolean hasNext() { return next < end; }
public Integer next() {
if (next >= end) throw new NoSuchElementException();
return next++;
}
};
}
@Override
public String toString() { return "[" + start + ", " + end + ")"; }
}
public class RangeDemo {
public static void main(String[] args) {
Range r = new Range(3, 8);
Range week = Range.closed(1, 7);
System.out.println(r + " length " + r.length() + ", week = " + week);
for (int i : r) System.out.print(i + " ");
System.out.println();
System.out.println("sum = " + r.stream().sum());
System.out.println(r.contains(3) + " " + r.contains(8));
System.out.println(r.overlaps(new Range(8, 10)) + " " + r.overlaps(new Range(7, 10)));
System.out.println(r.intersection(new Range(5, 20)));
System.out.println(r.intersection(new Range(10, 20)));
System.out.println(r.equals(new Range(3, 8)));
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
[3, 8) length 5, week = [1, 8)
3 4 5 6 7
sum = 25
true false
false true
Optional[[5, 8)]
Optional.empty
true
start 5 > end 1
- The compact constructor rejects
start > end, so everyRangeis valid. - The record stores the half-open form.
Range.closedconverts a closed range, andMath.addExactthrows instead of wrapping around whenlastisInteger.MAX_VALUE. - Two half-open ranges overlap when
start < r.end && r.start < end. Touching ranges such as[3, 8)and[8, 10)don't overlap. - Implementing
Iterable<Integer>makes the for-each loop work. For arithmetic,stream()returns anIntStreamso values aren't boxed. - The record supplies
equalsandhashCode, so ranges work as map keys and in sets.
Guava Range, RangeSet and RangeMap
When you need ranges of any Comparable type, unbounded ranges, or a set of ranges, use Guava (com.google.guava:guava:33.7.2-jre) instead of writing your own:
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.RangeSet;
import com.google.common.collect.TreeRangeMap;
import com.google.common.collect.TreeRangeSet;
import java.time.LocalDate;
public class GuavaRanges {
public static void main(String[] args) {
Range<Integer> closed = Range.closed(1, 10); // [1..10]
Range<Integer> open = Range.closedOpen(1, 10); // [1..10)
Range<Integer> atLeast = Range.atLeast(18); // [18..+inf)
System.out.println(closed + " " + open + " " + atLeast);
System.out.println(closed.contains(10) + " " + open.contains(10) + " " + atLeast.contains(99));
System.out.println(closed.intersection(Range.open(5, 20)));
System.out.println(closed.span(Range.closed(15, 20)));
System.out.println(closed.isConnected(Range.closed(11, 20)));
// works with any Comparable
Range<LocalDate> q1 = Range.closedOpen(LocalDate.of(2026, 1, 1), LocalDate.of(2026, 4, 1));
System.out.println(q1.contains(LocalDate.of(2026, 3, 31)));
Range<String> aToM = Range.closed("a", "m");
System.out.println(aToM.contains("kiwi") + " " + aToM.contains("pear"));
// iterate a range of integers
ContiguousSet<Integer> set = ContiguousSet.create(Range.open(1, 6), DiscreteDomain.integers());
System.out.println(set + " " + set.asList() + " size " + set.size());
// a set of disjoint ranges; adjacent ones are merged
RangeSet<Integer> busy = TreeRangeSet.create();
busy.add(Range.closedOpen(9, 11));
busy.add(Range.closedOpen(11, 12));
busy.add(Range.closedOpen(14, 16));
System.out.println(busy);
System.out.println(busy.complement().subRangeSet(Range.closedOpen(8, 18)));
// map ranges to values
RangeMap<Integer, String> tax = TreeRangeMap.create();
tax.put(Range.closedOpen(0, 10_000), "0%");
tax.put(Range.closedOpen(10_000, 50_000), "20%");
tax.put(Range.atLeast(50_000), "40%");
System.out.println(tax.get(9_999) + " " + tax.get(10_000) + " " + tax.get(1_000_000));
}
}
$ java -cp "guava-33.7.2-jre.jar;failureaccess-1.0.3.jar" GuavaRanges.java
[1..10] [1..10) [18..+∞)
true false true
(5..10]
[1..20]
false
true
true false
[2..5] [2, 3, 4, 5] size 4
[[9..12), [14..16)]
[[8..9), [12..14), [16..18)]
0% 20% 40%
(On Linux and macOS, separate the jars with : instead of ;.)
Range.closed,open,closedOpen,openClosed,atLeast,atMost,greaterThan,lessThanandallcreate ranges. Guava writes them in math notation:[and]include an end,(and)exclude it.- A
Rangeworks with anyComparable: numbers, strings,LocalDate, your own types. intersectionreturns the overlap and throws if there is none, so checkisConnectedfirst.spanreturns the smallest range that covers both.- A
Rangeis not a collection. To iterate over integers in it, wrap it in aContiguousSetwith aDiscreteDomain. TreeRangeSetstores a set of disjoint ranges and merges ranges that touch or overlap.complement()gives the gaps, which is handy for free time slots.TreeRangeMapmaps non-overlapping ranges to values, a fuller version of thefloorEntrylookup table above.
Summary
- Java has no range literal. Use a
forloop,IntStream.range/rangeClosed, orLongStreamforlongbounds. - JDK ranges are half-open:
[start, end). Length isend - start, and[0, n)covers the indexes of a collection of sizen. - For a step or a descending range, use
IntStream.iterate(seed, hasNext, next)ormapover an ascending range. - Don't loop up to
Integer.MAX_VALUEwith<=, and don't step through a range by adding to adouble. substring,subList,Arrays.copyOfRange,Arrays.filland friends take[from, to).subListreturns a view.- Use
Math.clampto force a value into a range andObjects.checkIndex/checkFromToIndexto validate indexes. TreeSet.subSetandTreeMap.subMapreturn range views of sorted data, andTreeMap.floorEntrylooks up which range a value falls into.LocalDate.datesUntiliterates over dates.- For ranges as values, write a small record, or use Guava's
Range,RangeSetandRangeMap.