Java OCA OCP Practice Question 2270

Question

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:  } 
  • A. 2-2
  • B. 200-1
  • C. 500-0
  • D. 500-2
  • E. The code does not compile.
  • F. The code compiles but throws an exception at runtime.


F.

Note

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.




PreviousNext

Related