Given:import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int a = IntStream.rangeClosed(1, 4).sum();
int b = IntStream.range(1, 4).sum();
System.out.println(a + " " + b);
}
}What is the result?
Choose one.
IntStream.range(start, end) excludes end; IntStream.rangeClosed(start, end) includes it.
Both factory methods produce ascending int streams starting at the first argument. range stops before the second argument, matching the familiar for (int i = start; i < end; i++) loop, so range(1, 4) is 1, 2, 3 with sum 6. rangeClosed stops at the second argument, so rangeClosed(1, 4) is 1, 2, 3, 4 with sum 10. sum() on an IntStream returns an int, so both assignments compile.
- Expand rangeClosed(1, 4): 1, 2, 3, 4.
- Expand range(1, 4): 1, 2, 3.
- Sum each stream: 10 and 6.
- Print a then b.
Exam tip: range is half-open like a for loop; rangeClosed includes both ends.
Java Streams, Lambdas and Primitive Streams (1Z0-831) — the lesson that teaches this.