Java OCA OCP Practice Question 1683

Question

What is the output of the following application?

package pet;//from  w  w  w .  java  2 s . c o m
import java.util.*;
import java.util.function.*;


public class Main {
   void reduceList(List<String> names, Predicate<String> tester) {
      names.removeIf(tester);
   }
   public static void main(String[] treats) {
      int MAX_LENGTH = 2;
      Main search = new Main();
      List<String> names = new ArrayList<>();
      names.add("123456");
      names.add("12345");
      names.add("12345");
      MAX_LENGTH += names.size();
      search.reduceList(names, d -> d.length()>MAX_LENGTH);
      System.out.print(names.size());
   }
}
  • A. 2
  • B. 3
  • C. The code does not compile because of lambda expression.
  • D. The code does not compile for a different reason.


C.

Note

The code does not compile, making Options A and B incorrect.

The local variable MAX_LENGTH is neither final nor effectively final, meaning it cannot be used inside the lambda expression.

The MAX_LENGTH variable starts off with an initial value of 2, but then is modified with the increment assignment (+=) operator to a value of 5, it is considered effectively final by the compiler.

Since the lambda does not compile, Option C is the correct answer.

If the code was rewritten so that the MAX_LENGTH variable was marked final and assigned a value of 5 from the start, then it would output 2, and Option A would be correct.




PreviousNext

Related