Java HashMap get() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, get(key) returns the value that a HashMap stores for key. If the map has no mapping for that key, it returns null instead of throwing an exception.

The map hashes the key to find the right bucket, then compares keys with equals(). That is why a lookup is usually constant time no matter how big the map is, and why keys need sensible equals and hashCode methods.

An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety.

Syntax

Pass the key; you get the value or null.

Java
Map<String, String> capitals = new HashMap<>();
capitals.put("Japan", "Tokyo");
String a = capitals.get("Japan");   // "Tokyo"
String b = capitals.get("Peru");    // null (no mapping)
CallWhat it does
map.get(key)The value for key, or null.
map.get(null)The value stored under the null key, if any.
map.containsKey(key)Tells "missing" apart from "mapped to null".

The parameter type is Object, not K, so the compiler accepts a key of the wrong type and the lookup quietly returns null.

Library declarations
Java
// java.util.HashMap<K, V>
public V get(Object key)

// Declared in Map<K, V>

Parameters

ParameterDescription
key (Object)The key to look up. May be null.

Return Value

Return ValueDescription
VThe value mapped to key.
nullNo mapping for key, or the key is mapped to null.

Compare with Similar Methods

Ways to read from a HashMap:

MethodHow it differs
getOrDefault(k, d)Returns a fallback instead of null for a missing key.
containsKey(k)Only answers whether the key exists.
computeIfAbsent(k, f)Reads the value, creating and storing it first when missing.

Java Examples

Example 1 — Look Up Capitals by Country

Store three countries, then look up two present keys, a missing key, and a key with different capitalization.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapGetDemo {
    public static void main(String[] args) {
        Map<String, String> capitals = new HashMap<>();
        capitals.put("France", "Paris");
        capitals.put("Japan", "Tokyo");
        capitals.put("Kenya", "Nairobi");

        System.out.println("Japan -> " + capitals.get("Japan"));
        System.out.println("Kenya -> " + capitals.get("Kenya"));
        System.out.println("Mars -> " + capitals.get("Mars"));
        System.out.println("japan -> " + capitals.get("japan"));
    }
}

How It Works

  1. Hash, then compare. get("Japan") hashes the string to pick a bucket and then checks the keys in that bucket with equals(), finding Tokyo without scanning the other countries.
  2. Missing key is not an error. No country is stored as "Mars", so get simply returns null and string concatenation prints the word null.
  3. Case matters. String.equals is case-sensitive, so "japan" and "Japan" are different keys and the lowercase lookup finds nothing.
  4. No side effects. None of the four lookups adds or changes anything; the map still holds exactly three countries afterwards.

Example 2 — null Results and the Unboxing Trap

An Integer map where one key holds null and another is missing. See why int age = map.get(...) can crash.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapGetNullTrap {
    public static void main(String[] args) {
        Map<String, Integer> ages = new HashMap<>();
        ages.put("Lina", 29);
        ages.put("Omar", null);

        System.out.println("Lina: " + ages.get("Lina"));
        System.out.println("Omar: " + ages.get("Omar") + ", has key: " + ages.containsKey("Omar"));
        System.out.println("Zed: " + ages.get("Zed") + ", has key: " + ages.containsKey("Zed"));

        Integer boxed = ages.get("Zed");
        if (boxed != null) {
            System.out.println("age " + boxed);
        } else {
            System.out.println("no age stored for Zed");
        }

        try {
            int age = ages.get("Zed");
            System.out.println("never printed " + age);
        } catch (NullPointerException e) {
            System.out.println("int age = ages.get(\"Zed\") threw NullPointerException");
        }
    }
}

How It Works

  1. Two kinds of null. Omar is stored with a null value and Zed is not stored at all, yet get returns null for both; only containsKey tells them apart.
  2. Keep the wrapper. Reading the result into an Integer variable is safe, and the boxed != null test decides what to print.
  3. Hidden unboxing. int age = ages.get("Zed") makes Java call intValue() on the returned null, which throws NullPointerException before the next line runs.
  4. Stable output. The catch block prints a fixed message rather than the exception text, because helpful NullPointerException messages differ between Java versions.

Example 3 — Wrong Key Type Returns null

A map with Long keys looked up with an int, plus a lookup with a different but equal String object.

Java
import java.util.HashMap;
import java.util.Map;

public class HashMapGetKeyType {
    public static void main(String[] args) {
        Map<Long, String> orders = new HashMap<>();
        orders.put(1001L, "keyboard");
        orders.put(1002L, "mouse");

        System.out.println("get(1001L): " + orders.get(1001L));
        System.out.println("get(1001): " + orders.get(1001));
        System.out.println("get(Long.valueOf(1002)): " + orders.get(Long.valueOf(1002)));

        Map<String, Integer> stock = new HashMap<>();
        stock.put("pen", 40);
        String typed = new String("pen");
        System.out.println("equal String object: " + stock.get(typed));
    }
}

How It Works

  1. Long keys. The L suffix makes 1001L a long literal, which is boxed to a Long key when it is stored.
  2. Silent mismatch. get(1001) boxes the literal to an Integer. Because get accepts any Object, this compiles, but Integer.equals never matches a Long, so the result is null.
  3. Convert first. Long.valueOf(1002) widens the int to a long and boxes it, so the key types agree and "mouse" is found.
  4. Equality, not identity. new String("pen") is a separate object from the stored key, but the two strings are equal and have the same hash code, so the lookup returns 40.

Frequently Asked Questions

It returns null. It does not throw an exception.
Call containsKey(key). get() returns null in both cases, but containsKey() returns true only when the key is present.
When get() returns null, Java tries to unbox it into an int and fails. Store the result in an Integer first, or use getOrDefault(key, 0).
Yes. With a reasonable hashCode() it takes constant time on average, because only one bucket is checked.
Yes. HashMap allows one null key, and get(null) returns its value or null if no null key is stored.

Next: getOrDefault()

Read a value, or a fallback when the key is missing.

getOrDefault() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful