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}

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/

Leave a Reply

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