How output defined in java map put?

Please let me know how output of below java code is defined

Map m=new HashMap();
m.put("A", "B");
m.put("A", m.put("A", "C"));

output:
A,B

till 2nd line it is A,B
after going in m.put("A","C") it is becoming A,C
last m.put("A", m.put("A", "C")); is taking key as "A" and value as "B"
please let me know how it works?

>Solution :

If you read the documentation for the put method you’ll notice that it returns

the previous value associated with key

So in this case m.put("A", "C") is returning "B" (because that’s what we put in the map with the previous statement) and storing "C", which gets immediately discarded by m.put("A", m.put("A", "C")); which is at that point equivalent to m.put("A", "B");

Leave a Reply