1Z0-819 · Question #175
Which of the following produces the same result as the given for loop? ``java for (int i = 1; i < 10; ++i) { System.out.println(i); } ``
The correct answer is B. Stream<Integer> nums2 = Stream.iterate(1, n -> n < 10, n + 1); forEach(System.out.println(n)). Option B correctly replicates the for loop because it uses Stream.iterate(1, n -> n < 10, n + 1), which starts at 1, stops before 10, and increments by 1 - matching i = 1, i < 10, and ++i exactly - and passes a valid consumer expression to forEach that prints each element. Why…
Question
for (int i = 1; i < 10; ++i) {
System.out.println(i);
}
Options
- AStream<Integer> nums1 = Stream.iterate(1, n -> n < 10, n + 2); forEach(System.out.println);
- BStream<Integer> nums2 = Stream.iterate(1, n -> n < 10, n + 1); forEach(System.out.println(n));
- CStream<Integer> nums3 = Stream.iterate(1, n -> n < 10, n + 1); forEach(System.out.println);
- DStream.iterate(1, n -> n < 10, n + 1).forEach(System.out.println);
How the community answered
(32 responses)- A9% (3)
- B84% (27)
- C3% (1)
- D3% (1)
Explanation
Option B correctly replicates the for loop because it uses Stream.iterate(1, n -> n < 10, n + 1), which starts at 1, stops before 10, and increments by 1 - matching i = 1, i < 10, and ++i exactly - and passes a valid consumer expression to forEach that prints each element.
Why the distractors fail:
- A is wrong because
n + 2increments by 2, producing1, 3, 5, 7, 9instead of1through9. - C uses the correct step (
n + 1) butforEach(System.out.println)is invalid -forEachrequires aConsumer<T>, andSystem.out.printlnwithout the method-reference operator (::) is not a valid consumer. - D has the same
forEachsyntax problem as C; writing the chain on one line doesn't fix the missing::.
Memory tip: Think of Stream.iterate's three arguments as matching the three parts of a for loop: (seed, condition, step) → (int i = 1, i < 10, ++i). And always remember that forEach needs a method reference (System.out::println) or a lambda (n -> System.out.println(n)) - never a bare method call.
Topics
Community Discussion
No community discussion yet for this question.