Java .put()

Anonymous contributor's avatar
Anonymous contributor
Published May 31, 2025
Contribute to Docs

In Java, the .put() method adds a key-value pair to a HashMap; if the key already exists, it updates the corresponding value.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

hashMap.put(key, value);

Parameters:

  • key: The key with which the given value is to be associated.
  • value: The value to be associated with the specified key.

Return value:

Returns the previous value associated with the specified key, or null if the key was not previously present in the map.

Example

This example demonstrates how to use the .put() method to add and update key-value pairs in a HashMap:

import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args){
HashMap<String, Integer> ages = new HashMap<String, Integer>();
// Adding key-value pairs to the HashMap
ages.put("Alice", 25);
ages.put("Bob", 27);
ages.put("Charlie", 30);
// Printing the HashMap
System.out.println("HashMap: " + ages);
// Updating the value for an existing key
Integer previousAge = ages.put("Alice", 26);
System.out.println("Previous age of Alice: " + previousAge);
System.out.println("Updated HashMap: " + ages);
}
}

The output of this code is:

HashMap: {Bob=27, Alice=25, Charlie=30}
Previous age of Alice: 25
Updated HashMap: {Bob=27, Alice=26, Charlie=30}

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours