Maps in Java: Quiz

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

Here are some quiz questions for you on maps in Java.

Questions

Q1. What will be the result?
Map<Integer, Integer> map = new HashMap<>();
map.put(1, 12);
map.put(12, 4);
map.replace(12, null); // Line 1
map.replace(11, 1);    // Line 2
System.out.println(map);

Choices

A. Does not compile
B. Throws exception
C. Prints {1=12, 12=null, 11=1}
D. Prints {1=12, 12=null}

Q2. What will be the result?
Map<Integer, String> map = new HashMap<Integer, String>();
int i = 1;
map.put(i, "Text1");
map.put(i, "Text2");
String s = map.getOrDefault(i++, null);
System.out.println(s);

Choices

A. Text1
B. Text2
C. null
D. Exception occurs

Answers

Q1. D is correct. It is allowed to pass null as a value to replace an existing value in the map as done in Line 1. However, Line 2 has no effect here because the map does not have a key 11. For more details on the replace() method, refer http://talks.skilltoz.com/replacing-values-in-a-map/

Q2. B is correct. As the passed key does not exist in the HashMap, getOrDefault() method returns the default value passed to it, which is null. For more details on the getOrDefault() method, refer http://talks.skilltoz.com/getting-values-from-a-hashmap/

Leave a Reply

Your email address will not be published. Required fields are marked *