Return to site

☕🎓JAVA CERTIFICATION QUESTION: Stream twice

· ocp,java

Given the following snippet:

What is the output?

* It prints successfully: 2, 4, 6 then 6

* It prints successfully: 2, 4, 6 twice

* It prints successfully: 2, 4, 6 then an IllegalStateException occurred

* It prints only 6

* The code does not compile

#java #certificationquestion #ocp

Answer: It prints successfully: 2, 4, 6 then an IllegalStateException occurred

The output is:

2

4

6

Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed

at java.base/java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)

at java.base/java.util.stream.ReferencePipeline.(ReferencePipeline.java:96)

at java.base/java.util.stream.ReferencePipeline$StatelessOp.(ReferencePipeline.java:800)

at java.base/java.util.stream.ReferencePipeline$2.(ReferencePipeline.java:167)

at java.base/java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:166)

at MyClass.main(MyClass.java:8)

 

This code will fail because streams in Java are designed to be consumed only once.

Once a terminal operation, such as forEach, is performed on a stream, the stream is considered consumed and cannot be reused.

In the code snippet, after the forEach operation is performed on the stream, it's considered consumed.

Therefore, when you try to perform another operation (filter followed by forEach) on the same stream, it will throw an IllegalStateException.