What is the output of the following?
1: package mypkg; 2: import java.util.stream.*; 3: // w w w . j a v a2 s. c om 4: public class Main { 5: public static void main(String[] args) { 6: IntStream pages = IntStream.of(200, 300); 7: long total = pages.sum(); 8: long count = pages.count(); 9: System.out.println(total + "-" + count); 10: } 11: }
F.
When summing int primitives, the return type is also an int.
Since a long is larger, you can assign the result to it, so line 7 is correct.
All the primitive stream types use long as the return type for count()
.
Therefore, the code compiles, and Option E is incorrect.
When actually running the code, line 8 throws an IllegalStateException because the stream has already been used.
Both sum()
and count()
are terminal operations and only one terminal operation is allowed on the same stream.
Therefore, Option F is the answer.