What is the HashTable.put() method in Java?

The HashTable.put() method is used to insert key-value pairs in a HashTable.

It is present in the HashTable class inside the java.util package.

Parameters

The HashTable.put() method takes two parameters:

  • key: The key for the value in the HashTable.
  • value: The value for the key in the HashTable.

Return value

The HashTable.put() method returns the following:

  • key: The previous value if an existing key is passed.
  • null: If a new pair is passed, then null is returned.

Code

Let’s look at the below code snippet to understand it better.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Hashtable<Integer, String> h1 = new Hashtable<Integer, String>();
h1.put(1, "Let's");
h1.put(5, "see");
h1.put(2, "Hashtable.contains()");
h1.put(27, "method");
h1.put(9, "in java.");
System.out.println(h1);
}
}

Explanation

  • In line 1, we imported the required package.
  • In line 2, we made a Main class.
  • In line 4, we made a main function.
  • In line 6, we declared a HashTable consisting of Integer type keys and String type values.
  • In lines 8 to 12, we inserted values in the HashTable by using the Hashtable.put() method.
  • In line 14, we print the HashTable.

In this way, we can use the HashTable.put() method to insert key-value pairs in the HashTable.

Free Resources