1Z0-809: Java SE 8 Programmer II Exam Question

Result of Code Fragment

Question

Given the code fragment: Map<Integer, String> books = new TreeMap<>(); books.put (1007, "A"); books.put (1002, "C"); books.put (1001, "B"); books.put (1003, "B"); System.out.println (books); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The code creates a new TreeMap object with key type Integer and value type String. The TreeMap class is a sorted map implementation in Java that orders its entries according to the natural ordering of the keys or a custom ordering if provided.

The code then adds four key-value pairs to the books map using the put method. The keys are integers and the values are strings.

Here's what happens for each of the put operations:

  1. books.put(1007, "A"); - adds the key-value pair (1007, "A") to the map.
  2. books.put(1002, "C"); - adds the key-value pair (1002, "C") to the map.
  3. books.put(1001, "B"); - adds the key-value pair (1001, "B") to the map.
  4. books.put(1003, "B"); - adds the key-value pair (1003, "B") to the map.

The order in which the key-value pairs are added to the map does not affect the order in which they are stored, since the TreeMap implementation orders the entries according to the natural ordering of the keys.

The System.out.println(books); statement then prints the entire map to the console.

Based on the natural ordering of the keys, the correct answer is option B: {1001 = B, 1002 = C, 1003 = B, 1007 = A}.

This is because the keys are sorted in ascending order, and for keys with the same value, the order of insertion is preserved. Therefore, the output will be sorted by the keys, and the values associated with the keys will be printed in the order they were inserted.

Note that the other answer choices are not correct because they do not reflect the natural ordering of the keys in a TreeMap.