Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Hard
Question 32
Given code of Test.java file:
- package com.udayan.ocp;
- import java.util.ArrayList;
- import java.util.List;
- public class Test {
- public static void main(String[] args) {
- int ref = 10;
- List<Integer> list = new ArrayList<>();
- list.stream().anyMatch(i -> {
- System.out.println("HELLO");
- return i > ++ref;
- });
- }
- }
What will be the result of compiling and executing Test class?
-
A
Program executes successfully but nothing is printed on to the console
- B Compilation error
- C HELLO
Reveal correct answer
Correct answer: B
Explanation
Method signature for anyMatch method:
boolean anyMatch(Predicate<? super T>) : Returns true if any of the stream element matches the given Predicate. If stream is empty, it returns false and predicate is not evaluated.
ref is a local variable and it is used within lambda expression.
++ref causes compilation failure as variable ref should be effectively final.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
You must be logged in to post a comment.
