Maps in Java: Quiz

For Java 11 Certification Exam Practice Questions, refer

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


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


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);


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


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

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

Leave a Reply

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