LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Find the Error · Question 5

Error: assigning a map value to the wrong type Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> age = new HashMap<>();
        age.put("Asha", 21);
        String a = age.get("Asha");
        System.out.println(a);
    }
}
  • A get needs a default
  • B get returns an Integer (the value type), which cannot be assigned to a String; use Integer a or String.valueOf(...) Correct
  • C Asha must be a key object
  • D age must be a TreeMap
Correct Answer: Option B

javac: "incompatible types: Integer cannot be converted to String".

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