Junior — Middle
Is it safe to attempt to get a value from a HashMap using a key that does not exist?
sobes.tech AI
Answer from AI
In Java, when attempting to retrieve a value from a HashMap using a key that does not exist, the get() method returns null. This is safe in terms of avoiding exceptions — the program will not crash. However, it is important to consider that null can mean either the key is absent or that the key is explicitly mapped to a null value.
Example:
HashMap<String, String> map = new HashMap<>();
map.put("key1", "value1");
String value = map.get("key2"); // returns null because the key "key2" does not exist
if (value == null) {
System.out.println("Key not found or value is null");
}
If it is important to distinguish between a missing key and a null value, you can use the containsKey() method.