Machine-translated by Google. Questions are authored in English.
Top

Objects and Collections - Finding the output Questions and Answers

41.

What will be the output of the program?

import java.util.*;

public class Example41
{
    static class Person implements Comparable<Person>
    {
        String name;
        Person(String name) { this.name = name; }

        public int compareTo(Person other)
        {
            return name.compareTo(other.name);
        }

        public String toString() { return name; }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>(
            Arrays.asList(new Person("zoe"), new Person("amy")));
        Collections.sort(people);
        System.out.println(people);
    }
}

Answer: A

Collections.sort uses the natural ordering, which Person supplies by implementing Comparable, so the list is ordered by name and prints [amy, zoe]. Overriding toString is what makes the output readable; without it each element would print as a class name and a hash.

Please log in or register to report this question.

42.

What will be the output of the program?

import java.util.*;

public class Program42
{
    static class Person
    {
        String name;
        Person(String name) { this.name = name; }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>(
            Arrays.asList(new Person("zoe"), new Person("amy")));
        Collections.sort(people);
        System.out.println(people.size());
    }
}

Answer: B

Collections.sort requires its element type to extend Comparable, and the compiler enforces that through the method's generic signature, so this is rejected before it can run. The raw-typed equivalent from before generics would instead have compiled and thrown ClassCastException at runtime.

Please log in or register to report this question.

43.

What will be the output of the program?

import java.util.*;

public class Trial43
{
    public static void main(String[] args)
    {
        List<Integer> scores = new ArrayList<Integer>(
            Arrays.asList(70, 95, 82));
        Collections.sort(scores, Collections.reverseOrder());
        int top = scores.get(0);
        Collections.sort(scores);
        System.out.println(top + " " + scores.get(0) + " " + scores);
    }
}

Answer: C

reverseOrder returns a comparator that inverts the natural ordering, so the first sort puts the highest score first and top reads 95. Sorting again without a comparator restores ascending order, so the same position now holds 70. Each sort rearranges the list in place; nothing is returned.

Please log in or register to report this question.

44.

What will be the output of the program?

import java.util.*;

public class Case44
{
    public static void main(String[] args)
    {
        Set<String> s = new TreeSet<String>(
            new Comparator<String>()
        {
            public int compare(String x, String y)
            {
                return x.length() - y.length();
            }
        });
        s.add("aa");
        s.add("bb");
        System.out.println(s.size() + " " + s);
    }
}

Answer: D

A sorted set decides duplicates with its comparator, not with equals. This comparator reports two strings of the same length as equal, so bb is treated as already present and rejected, leaving one element. The javadoc calls a comparator inconsistent with equals well-defined but surprising, and this is why.

Please log in or register to report this question.

45.

What will be the output of the program?

import java.util.*;

public class Sketch45
{
    public static void main(String[] args)
    {
        List<String> plan = new ArrayList<String>(
            Arrays.asList("draft", "review", "ship"));
        ListIterator<String> steps = plan.listIterator();
        steps.next();
        steps.set("outline");
        steps.add("sketch");
        System.out.println(plan);
    }
}

Answer: A

set replaces the element the iterator has just returned, so draft becomes outline. add then inserts before the implicit cursor, which sits after that element, placing sketch second. Both go through the iterator, so neither upsets it; only modifying the list directly would.

Please log in or register to report this question.

46.

What will be the output of the program?

import java.util.*;

public class Item46
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>();
        Iterator<String> it = l.iterator();
        System.out.println(it.hasNext());
        it.next();
    }
}

Answer: B

An iterator over an empty collection reports hasNext as false, which prints, and calling next anyway throws NoSuchElementException rather than returning null. Checking hasNext before every next is what the contract expects.

Please log in or register to report this question.

47.

What will be the output of the program?

import java.util.*;

public class Sample47
{
    public static void main(String[] args)
    {
        Map<String, Integer> m = new TreeMap<String, Integer>();
        m.put("b", 2); m.put("a", 1);
        for (Map.Entry<String, Integer> e : m.entrySet())
        {
            e.setValue(e.getValue() * 10);
        }
        System.out.println(m);
    }
}

Answer: C

An entry obtained during iteration is a view onto the map, so setValue writes straight through and the stored values change. A TreeMap keeps its keys sorted, so the output is {a=10, b=20}. Changing a value is not a structural modification and does not upset the iterator.

Please log in or register to report this question.

48.

What will be the output of the program?

import java.util.*;

public class Probe48
{
    public static void main(String[] args)
    {
        List<String> words = new ArrayList<String>(
            Arrays.asList("pear", "fig", "banana"));
        String longest = Collections.max(words, new Comparator<String>()
        {
            public int compare(String x, String y)
            {
                return x.length() - y.length();
            }
        });
        System.out.println(longest + " " + Collections.max(words));
    }
}

Answer: D

The first call supplies a comparator ranking by length, so it returns banana. The second uses the natural ordering of String, which is lexicographic, and p sorts after b and f, so it returns pear. Same collection, two different maxima, decided entirely by the ordering in force.

Please log in or register to report this question.

49.

What will be the output of the program?

import java.util.*;

public class Demo49
{
    public static void main(String[] args)
    {
        List<String> l = new ArrayList<String>(
            Arrays.asList("a", "b", "c"));
        List<String> view = l.subList(0, 2);
        view.set(0, "z");
        System.out.println(l);
    }
}

Answer: A

Correct answer: The program prints [z, b, c]

subList returns a *view* onto the backing list, not a copy, so writing through the view writes through to the original: setting index 0 of the view sets index 0 of the list. Printing l therefore shows [z, b, c] - the whole list, with only the first element changed. The view is also fragile: structurally modifying the backing list through any other route invalidates it.

Please log in or register to report this question.

50.

What will be the output of the program?

import java.util.*;

public class Snippet50
{
    public static void main(String[] args)
    {
        Map<Character, List<String>> index =
            new HashMap<Character, List<String>>();
        for (String w : new String[] {"ant", "ape", "bee"})
        {
            char k = w.charAt(0);
            if (!index.containsKey(k)) index.put(
                k, new ArrayList<String>());
            index.get(k).add(w);
        }
        System.out.println(index.get('a').size() + " " + index.size());
    }
}

Answer: B

This is the grouping idiom: containsKey decides whether a bucket exists, and get returns the SAME list each time so the appends accumulate. Two words start with a, giving a list of 2, and there are two distinct first letters, so the map holds 2 entries. get returns the stored reference, not a copy.

Please log in or register to report this question.

Loading…
Tags: Objects and Collections - Finding the output Questions and Answers || Objects and Collections - Finding the output MCQ Questions and Answers || Objects and Collections - Finding the output GK Questions and Answers || Objects and Collections - Finding the output GK MCQ Questions || Objects and Collections - Finding the output Multiple Choice Questions and Answers || Objects and Collections - Finding the output GK || GK on Objects and Collections - Finding the output || Java Programming Questions and Answers || Java Programming MCQ Questions and Answers || Java Programming GK Questions and Answers || GK on Java Programming