Java HashMap put() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
HashMap

Definition

In Java, put(key, value) stores value under key in a HashMap. If the key is new, a mapping is added and the size grows by one. If the key already exists, its old value is replaced and the size stays the same.

The method returns the previous value for the key, or null when there was none. HashMap accepts one null key and any number of null values. Adding is constant time on average; when the map gets about three-quarters full, it grows its table and redistributes the entries.

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 a key and a value; you get the old value back.

Java
Map<String, String> phones = new HashMap<>();
String a = phones.put("Asha", "555-0101");   // null (new key)
String b = phones.put("Asha", "555-0177");   // "555-0101" (replaced)
CallWhat it does
map.put(k, v)Adds or replaces; returns the old value or null.
map.put(k, map.get(k) + 1)Update based on the old value (key must exist).
map.put(null, v)Stores a value under the single null key.
map.putIfAbsent(k, v)Adds only when the key is missing.

Values are autoboxed: map.put("Ivy", 72) stores an Integer in a Map<String, Integer>.

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

// Declared in Map<K, V>

Parameters

ParameterDescription
key (K)The key. May be null. Should have consistent equals and hashCode.
value (V)The value to store. May be null.

Return Value

Return ValueDescription
VThe previous value for key.
nullThe key was new, or it was previously mapped to null.

Compare with Similar Methods

Ways to store values:

MethodHow it differs
putIfAbsent(k, v)Never overwrites an existing non-null value.
putAll(m)Copies every mapping from another map.
replace(k, v)Only replaces; never adds a new key.
merge(k, v, f)Combines the new value with the old one.

Java Examples

Example 1 — Build a Phone Book and Read put()'s Return Value

Add two contacts, update one number, and print what each put returned.

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

public class HashMapPutDemo {
    public static void main(String[] args) {
        Map<String, String> phoneBook = new HashMap<>();
        String first = phoneBook.put("Asha", "555-0101");
        String second = phoneBook.put("Ben", "555-0199");
        String replaced = phoneBook.put("Asha", "555-0177");

        System.out.println("first put returned: " + first);
        System.out.println("second put returned: " + second);
        System.out.println("overwrite returned: " + replaced);
        System.out.println(phoneBook + " size " + phoneBook.size());
    }
}

How It Works

  1. New keys return null. Asha and Ben were not in the map, so the first two calls return null.
  2. Overwrite returns the old value. Putting Asha again replaces her number and returns the one that was there, 555-0101.
  3. Keys stay unique. Three calls produced two mappings; the updated number simply sits in Asha's existing entry.
  4. Hash order. Asha prints before Ben because of the buckets the two names hash to; that she was added first is a coincidence, not the reason.

Example 2 — Update Marks, Store null, and Replace a null Value

Raise a mark using its old value, store a null key and a null value, then replace that null.

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

public class HashMapPutNulls {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Ivy", 72);
        marks.put("Ivy", marks.get("Ivy") + 5);
        marks.put(null, 0);
        marks.put("Jay", null);

        System.out.println("Ivy: " + marks.get("Ivy"));
        System.out.println("null key: " + marks.get(null));
        Integer prev = marks.put("Jay", 64);
        System.out.println("Jay was " + prev + ", now " + marks.get("Jay"));
        System.out.println(marks);
    }
}

How It Works

  1. Read-modify-write. marks.get("Ivy") + 5 unboxes 72, adds 5, and put stores 77 back under the same key.
  2. One null key. put(null, 0) is allowed in a HashMap; get(null) reads it back.
  3. null values too. Jay is stored with a null mark, so the next put for Jay returns null as the previous value.
  4. Bucket 0. The null key is always stored in bucket 0, the first bucket visited, so here it prints before Jay and Ivy.

Example 3 — A Changed Key Strands Its Entry

Use a List as a key, change the list, and try to find the entry again.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapPutMutableKey {
    public static void main(String[] args) {
        List<String> team = new ArrayList<>(Arrays.asList("Ann", "Bo"));
        Map<List<String>, String> projects = new HashMap<>();
        projects.put(team, "Website");
        System.out.println("before change: " + projects.get(team));

        team.add("Cy");
        System.out.println("after change: " + projects.get(team));
        System.out.println("containsKey: " + projects.containsKey(team) + ", size " + projects.size());

        List<String> original = new ArrayList<>(Arrays.asList("Ann", "Bo"));
        System.out.println("lookup with an equal list: " + projects.get(original));
    }
}

How It Works

  1. Hash fixed at put time. When the list is stored, the map records its hash code, which is computed from the elements Ann and Bo.
  2. Key changed afterwards. Adding Cy changes the list's hash code, so get(team) searches with a different hash and finds nothing.
  3. Entry still there. The size is still 1: the mapping exists but cannot be reached with the changed key.
  4. Equal list fails too. A new [Ann, Bo] list has the old hash, but the stored key now equals [Ann, Bo, Cy], so equals fails. Use immutable keys such as String.

Frequently Asked Questions

The previous value for the key, or null if the key was not present (or was mapped to null).
The old value is replaced by the new one. The size does not change and put() returns the old value.
Yes. It allows one null key and any number of null values.
Use putIfAbsent(key, value), or computeIfAbsent(key, k -> ...) when creating the value is expensive.
Its hash code changed, so the map looks in the wrong place. Never modify an object while it is used as a map key.

Next: putAll()

Copy every mapping from another map.

putAll() 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.

12 people found this page helpful