LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Predict the Output · Question 1

The value returned by put Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<>();
        Integer a = m.put("x", 1);
        Integer b = m.put("x", 2);
        Integer c = m.put("y", 3);
        System.out.println(a + " " + b + " " + c + " " + m.get("x") + " " + m.size());
    }
}
  • A null 1 null 2 2 Correct
  • B null null null 2 3
  • C 1 2 3 2 2
  • D null 1 null 1 2
Correct Answer: Option A

put returns the previous value (null if none); the second put replaces 1 with 2.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links