Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 4
Question ID: UKOCP63850
Given code:
- package com.udayankhattry.ocp;
- import java.util.*;
- public class Test {
- public static void main(String[] args) {
- var list = new ArrayList<String>(List.of("T", "O", "A", "S", "L", "M")); //Line n1
- list.sort((var x1, var x2) -> -2 * x1.compareTo(x2)); //Line n2
- list.forEach(System.out::print); //Line n3
- }
- }
What is the result?
- A Compilation error
- B An exception is thrown at runtime
- C TSOMLA
- D ALMOST
Reveal correct answer
Correct answer: C
Explanation
UKOCP63850:
At Line n1, 'list' infers to ArrayList<String> and it refers to a List object containing 6 elements: ["T", "O", "A", "S", "L", "M"].
List<E> interface has below sort method:
default void sort(Comparator<? super E> c) {...}
Lambda expression (var x1, var x2) -> -2 * x1.compareTo(x2) is the correct implementation of Comparator<String> interface. It invokes the compareTo(String) method of String class, which compares two strings lexicographically and
returns 0, if the strings are equal
returns a negative number, x1 lexicographically precedes x2
returns a positive number, x1 lexicographically follow x2
If we use the compareTo method of String class, inside our Comparator, then Strings will be sorted in ascending order, in this case "A", "L", "M", "O", "S", "T".
But as we are multiplying the result of comareTo method with -2, it changes the negative number to positive number and positive number to negative number. Hence, the given comparator (at Line n2) would sort the Strings in descending order, in this case "T", "S", "O", "M", "L", "A".
After successful execution, Line n2 sorts the list to ["T", "S", "O", "M", "L", "A"].
Iterable<T> interface has forEach(Consumer<? super T>) method. List<E> extends Collection<E> & Collection<E> extends Iterable<E>, therefore forEach(Consumer) can easily be invoked on reference variable of List<E> type.
As Consumer is a Functional Interface, hence a lambda expression can be passed as argument to forEach() method.
forEach(Consumer) method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
The lambda expression at Line n3 is the correct implementation of Consumer<String> interface. It compiles successfully and on execution prints each element of the list. Hence, output is: TSOMLA
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
