Java: IntStream.rangeClosed for numeric ranges

IntStream generates primitive int ranges you can sum or map without boxing.

Code
int sum = IntStream.rangeClosed(1, 100).sum();
System.out.println("1..100 = " + sum);
int[] squares = IntStream.rangeClosed(1, 5).map(n -> n * n).toArray();
System.out.println(Arrays.toString(squares));
Output
1..100 = 5050
[1, 4, 9, 16, 25]
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26