nerdexam
Oracle

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…

Working with Streams and Lambda Expressions

Question

Which of the following produces the same result as the given for loop?
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)
  • A
    9% (3)
  • B
    84% (27)
  • C
    3% (1)
  • D
    3% (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 + 2 increments by 2, producing 1, 3, 5, 7, 9 instead of 1 through 9.
  • C uses the correct step (n + 1) but forEach(System.out.println) is invalid - forEach requires a Consumer<T>, and System.out.println without the method-reference operator (::) is not a valid consumer.
  • D has the same forEach syntax 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

#Stream.iterate()#method references#lambda expressions#loop equivalence

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice