Oracle Certified Professional Java Se 11 Developer · Free Practice Question Easy
Question 53
Question ID: UKOCP16668
Given code:
- package com.udayankhattry.ocp;
- import java.util.*;
- public class Test {
- public static void main(String[] args) {
- Collection<Integer> list = List.of(100, 100, 100); //Line n1
- Collection<Integer> set = new LinkedHashSet<>(list); //Line n2
- set.forEach((set) -> System.out.print(set)); //Line n3
- }
- }
What is the result?
- A Line n1 causes compilation error
- B Line n2 causes compilation error
- C Line n3 causes compilation error
- D Line n2 throws Runtime Exception
- E 100
- F 100100100
Reveal correct answer
Correct answer: C
Explanation
UKOCP16668:
Line n1 compiles fine.
All concrete classes of Collection type have one overloaded constructor accepting a parameter of Collection type. For example, LinkedHashSet<E> has below constructor:
public LinkedHashSet(Collection<? extends E> c) {...}
Hence, Line n2 compiles fine.
At Line n3, lambda parameter 'set' has already been declared in the enclosing scope and that is why Line n3 causes compilation error.
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.
