Return to site

JAVA CERTIFICATION QUESTION: stream and limit

· java,ocp

Given:

What is the output of the given code fragment?

  • 01
  • 012
  • Nothing
  • An exception is thrown
  • Compilation fails

#java #certificationquestion #ocp

 

 

 

Answer: 01

When the terminal operation is performed, each element of the source goes through the whole pipeline from the beginning to the end.

With the limit operation in place, the stream is truncated to only two elements.

Notice: This is true regardless of the position of the limit operation in the pipeline (of course it must be put before the terminal operation).

Consequently, just the first two numbers are printed to the console, while the last one is never handled.