1. Question
Go through the given Java program. The program adds key-value pairs in the TreeMap which already has a few key-value pairs.
Predict the output.
Map<String, String> map = new TreeMap<>();
map.put("test key 1", "test value 1");
map.put("test key 2", "test value 2");
map.put("test key 3", "test value 3");
System.out.println( map.put("test key 3", "test value 3") );
System.out.println( map.put("test key 4", "test value 4") );
2. Answer
The program outputs:
test value 3
null
Can anyone please explain why option b is giving us such behavior?
3. Reasoning
If we look at Map.put()
operation, it returns the value if the key-value is already present in the Map. Or we can say when the put() operation updates an existing Map entry.
After adding the key “test key 3”, when we add it a second time, it returns the value “test value 3”.
But, when we add “test key 4” which is the first-time entry, it is not present in Map, so the map returns its value as null.
Happy Learning !!