Java MCQs – Java 8 Features

31.) Which terminal operation in the Streams API returns the first element of the stream, or a default value if the stream is empty?

A) findFirst()
B) findAny()
C) getFirst()
D) getAny()

Answer: Option A

Explanation: The findFirst() terminal operation returns the first element or a default value if the stream is empty.

32.) Can a class inherit a default method with the same name from multiple interfaces?

A) No, it results in a compilation error.
B) Yes, but the class must override the method.
C) Yes, and it can choose which method to use.
D) No, interfaces cannot have methods with the same name.

Answer: Option C

Explanation: A class can inherit default methods with the same name from multiple interfaces and choose which one to use.

33.) What does the flatMap() intermediate operation do in the Streams API?

A) It maps each element to a new element.
B) It transforms a stream of streams into a single stream.
C) It filters elements based on a predicate.
D) It counts the elements in the stream.

Answer: Option B

Explanation: The flatMap() operation transforms a stream of streams into a single stream.

34.) In parallel streams, which factor determines the number of CPU cores used for parallel processing?

A) Number of stream elements
B) JVM heap size
C) Explicitly set parallelism level
D) Number of available threads

Answer: Option C

Explanation: The parallelism level can be explicitly set to control the number of CPU cores used.

35.) Which method reference syntax is used for instance method references?

A) Class::staticMethod
B) Class::instanceMethod
C) ::instanceMethod
D) ::new

Answer: Option B

Explanation: Class::instanceMethod is the syntax for instance method references.

36.) In the Optional class, what method is used to perform an action only if a value is present?

A) ifPresent()
B) orElse()
C) ifNull()
D) orElseGet()

Answer: Option A

Explanation: The ifPresent() method is used to perform an action if a value is present in an Optional.

Leave a Reply

Your email address will not be published. Required fields are marked *