Topics Index


If you need explanation Read this topic

If you need Answer Take test on this topic

What will be the output of the following program?
import java.util.*;
public class Person implements Comparator<Person>, Comparable<Person> {
    String name;
    int age;
    Person(String n, int a) {    name = n;    age = a;    }
    public String toString() {    return name + "~" + age;    }
    public static void main(String args[]) {
        List<Person> list = new ArrayList<Person>();
        Person jason = new Person("Jason", 22);
        list.add(new Person(null, 21));
        list.add(new Person("Advin", 25));
        list.add(new Person("Advin", 30));
        list.add(new Person("Tom", 24));
        list.add(new Person(null, 23));
    public static int nullSafeStringComparator(final String one, final String two) {
        if (one == null ^ two == null)    return (one == null) ? -1 : 1;
        if (one == null && two == null)    return 0;
        return one.compareTo(two);
    public int compareTo(final Person d) {
        int result = nullSafeStringComparator(name,;
        if (result != 0)
            return result;
        return compare(d, this);
    public int compare(Person d, Person d1) {    return d.age - d1.age;    }

A. [null~23, null~21, Advin~30, Advin~25, Jason~22, Tom~24]
B. [null~21, null~23, Advin~25, Advin~30, Jason~22, Tom~24]
C. [Advin~30, Advin~25, Jason~22, Tom~24, null~23, null~21]
D. [Advin~25, Advin~30, Jason~22, Tom~24, null~21, null~23]
E. Some other output
F. Compilation Error or Runtime Error
Topic: Java Comparators

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

F.runtime error occurs due to araise of NullPointer Exception

Posted by Shabaaz Shaikz    2014-02-26 13:00:50

Here Person objects are sorted based on their names (dictionary order) and if the names are found to be same, then sorting is done based on their ages (descending order because of the expression {d.age - d1.age} in the compare() method). nullSafeStringComparator() method returns -1 if the first String object is null. So, a null value comes before any other String value and the case where two String objects are null or two String values are equal is handled by "compare" method using corresponding "age" values. So, the answer is A.

Posted by Shaileshwar Sharma    2014-02-26 17:13:55

Congratulations Shaileshwar Sharma. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-02-27 04:20:38

© meritcampus 2019

All Rights Reserved.

Open In App