Oracle Certified Professional Java Se 11 Developer · Free Practice Question Hard
Question 12
Question ID: UKOCP26465
Given code of Test.java file:
- package com.udayankhattry.ocp;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.List;
- class Student implements Comparator<Student> {
- private String name;
- private String exam;
- public Student() {
- super();
- }
- public Student(String name, String exam) {
- this.name = name;
- this.exam = exam;
- }
- public int compare(Student s1, Student s2) {
- return s2.name.compareToIgnoreCase(s1.name);
- }
- public String toString() {
- return '{' + name + ", " + exam + '}';
- }
- }
- public class Test {
- public static void main(String[] args) {
- Student stud1 = new Student("John", "OCA");
- Student stud2 = new Student("Jack", "OCP");
- Student stud3 = new Student("Rob", "OCP");
- List<Student> list = Arrays.asList(stud1, stud2, stud3);
- list.sort(new Student());
- list.forEach(System.out::println);
- }
- }
What is the result?
- A Runtime exception
- B Compilation error
-
C
{Rob, OCP}
{John, OCA}
{Jack, OCP}
-
D
{Jack, OCP}
{John, OCA}
{Rob, OCP}
Reveal correct answer
Correct answer: C
Explanation
UKOCP26465:
In real-world programming, you will hardly find a bean class implementing Comparator, but it is a legal code. A bean class generally implements a Comparable interface to define natural ordering.
Student class in this case correctly implements Comparator<Student> interface by overriding compare(Student, Student) method. Note, this compare method will sort in descending order of the Student's name.
list.sort(...) accepts an argument of Comparator<Student> type. new Student() provides the instance of Comparator<Student> type. It sorts the list in descending order of Students' names.
Output is:
{Rob, OCP}
{John, OCA}
{Jack, OCP}
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
