Java OCA OCP Practice Question 2215

Question

Choose the best option based on this program:

import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public class Main {
    public static void main(String []args) {
        IntStream temperatures = IntStream.of(-5, -6, -7, -5, 2, -8, -9);
        IntPredicate positiveTemperature = temp -> temp > 0;   // #1

        if(temperatures.anyMatch(positiveTemperature)) {       // #2
             int temp = temperatures
                              .filter(positiveTemperature)
                              .findAny()
                              .getAsInt();                    // #3
            System.out.println(temp);
        }/*  w w  w  .  j  a  v  a  2s .co  m*/
    }
}
  • A. this program results in a compiler error in line marked with comment #1
  • B. this program results in a compiler error in line marked with comment #2
  • C. this program results in a compiler error in line marked with comment #3
  • D. this program prints: 2
  • e. this program crashes by throwing java.lang.IllegalStateException


e.

Note

a stream once used-i.e., once "consumed"-cannot be used again.

In this program, anyMatch() is a terminal operation.

hence, once anyMatch() is called, the stream in temperatures is considered "used" or "consumed".

hence, calling findAny() terminal operation on temperatures results in the program throwing java.lang.IllegalStateException.




PreviousNext

Related