.put()
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.
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 HashMapages.put("Alice", 25);ages.put("Bob", 27);ages.put("Charlie", 30);// Printing the HashMapSystem.out.println("HashMap: " + ages);// Updating the value for an existing keyInteger 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: 25Updated HashMap: {Bob=27, Alice=26, Charlie=30}
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours