Java puzzle – TreeMap put operation

Puzzle : I have given a below map with the following below options,

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

Option A) System.out.println(map.put(“test key 3”, “test value 3”));
Answer) This prints the output as = test value 3

Option B) System.out.println(map.put(“test key 4”, “test value 4”));
Answer) This prints the output as = null;

Can anyone please explain why option b is giving us such a behavior?

Also when I print the map after the Option B sysout statement, I have the test key 4 present in it?

Solution : If you look at Map.put() operation, it returns the value if key is already present in map.

After adding key “test key 3”, when again try to add it, it returns the value “test value 3”.

When you add “test key 4” first time, it is no present in map, so map return’s it’s value is null.

Next time when you store “test key 4”, this time entry is already present so value is returned as “test value 4”

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial