Java OCA OCP Practice Question 1673

Question

Given the following class, how many lines contain compilation errors?

1:  package mypkg;
2:  import java.util.*;
3:  import java.util.function.*;
4:  public class Main {
5:     private Function<String> printer;
6:     protected Main() {
7:         printer = s -> {System.out.println(s); return s;}
8:     }//w w w.j a  v a 2  s.co  m
9:     void printRectangles(List<String> l) {
10:       l.forEach(printer);
11:    }
12:    public static void main(String[] screen) {
13:       List<String> l = new ArrayList<>();
14:       l.add("A");
15:       l.add("B");
16:       l.add("C");
17:       new Main().printRectangles(l);
18:    }
19: }
  • A. None. The code compiles as is.
  • B. One
  • C. Two
  • D. Three


D.

Note

To start with, line 5 does not compile because Function takes two generic arguments, not one.

Second, the assignment statement on line 7 does not end with a semicolon (;), so it also does not compile.

The forEach() method on line 10 requires a Consumer, not a Function, so this line does not compile.

Option D is the correct answer.




PreviousNext

Related