VOOZH about

URL: https://www.geeksforgeeks.org/java/java-hashtable-put-method/

⇱ Java Hashtable put() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Hashtable put() Method

Last Updated : 22 May, 2025

The Hashtable.put() method is a part of java.util package. This method is used to insert a mapping into a table. This means we can insert a specific key and the value it maps to into a particular table. If an existing key is passed, then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.

Syntax of Hashtable put() Method

Below is the syntax of put() method.

Hash_Table.put(key, value)

Parameters:

This method takes two parameters, both of the Object type of the Hashtable.

  • key: This refers to the key element that needs to be inserted into the table for mapping.
  • value: This refers to the value that the above key will map to.

Return Value: If an existing key is passed, the previous value gets returned. If a new pair is passed, then null is returned.

Examples of Java Hashtable put() Method

Example 1: In this example, we are going to use the put() method when an existing key is passed.


Example 2: In this example, let's use the put() method when a new key is passed and we will see what it prints.


Important Points:

  • The put() method replaces the value if the key is already exists.
  • The method returns the previous value associated with the key or it returns null if the key was not present.
  • This method works with any combination of data types as the key and value.
Comment
Article Tags: