Question discussion

What is the output of the following Java program?import java.util.*; public class Main { public static void main(String[] args) { TreeMap m…

1984Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

import java.util.*;
public class Main {
    public static void main(String[] args) {
        TreeMap<String, Integer> m = new TreeMap<>();
        m.put("c", 5);
        m.put("a", 1);
        m.put("b", 2);
        m.put("a", 9);
        System.out.println(m.firstKey() + m.lastEntry().getValue() + m.size());
    }
}
  • Ac53
  • Ba93
  • Ca33
  • Da53
Correct answer: D

Explanation

A TreeMap is sorted by key, so firstKey() is "a", lastEntry() is c=5, and re-putting "a" only replaces its value, so size() stays 3 - giving "a" + 5 + 3 = a53.

Discussion 0

Nobody has replied yet. Start the discussion!