Java Hashtable containsKey() Method
Last Updated :
16 May, 2025
The Hashtable.containsKey() is a built-in method in the Java Hashtable class. When we work with Java Hashtable class, it becomes necessary to check whether the key is present in the table before trying to access its value. So, to do this, there is a method called containsKey().
This method is used to check if a key present in the hashtable or not. This method returns true if the key is present, otherwise it returns false.
Syntax of Hashtable containsKey() Method
hash_table.containsKey(key_element);
- Parameters: This method accepts one parameter i.e., key_element, which refers to the key whose presence is supposed to be checked inside a Hashtable.
- Return Value: This method returns boolean true if the key is present in the Hashtable otherwise, it returns false.
Examples of Java Hashtable containsKey() Method
Example 1: In this example, we are going to create a Hashtable with Integer keys and String values, and then we will check for some keys using containsKey() method.
Java
// Java program to demonstrate the containsKey() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Create an empty Hashtable
Hashtable<Integer, String> ht = new Hashtable<Integer, String>();
// Put values into the table
ht.put(10, "Geeks");
ht.put(15, "4");
ht.put(20, "Geeks");
ht.put(25, "Welcomes");
ht.put(30, "You");
System.out.println("The Hashtable is: "
+ ht);
// Check for key 20
System.out.println("Is the key '20' present? "
+ ht.containsKey(20));
// Check for key 5
System.out.println("Is the key '5' present? "
+ ht.containsKey(5));
}
}
OutputThe Hashtable is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Is the key '20' present? true
Is the key '5' present? false
Example 2: In this example, we will create a Hashtable with String keys and Integer values.
Java
// Java program to demonstrate the containsKey() method
import java.util.*;
public class Geeks {
public static void main(String[] args) {
// Create an empty Hashtable
Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
// Put values into the table
ht.put("Geeks", 10);
ht.put("4", 15);
ht.put("Geeks", 20);
ht.put("Welcomes", 25);
ht.put("You", 30);
System.out.println("The Hashtable is: " + ht);
// Check for key "Welcomes"
System.out.println("Is the key 'Welcomes' present? "
+ ht.containsKey("Welcomes"));
// Check for key "World"
System.out.println("Is the key 'World' present? "
+ ht.containsKey("World"));
}
}
OutputThe Hashtable is: {You=30, Welcomes=25, 4=15, Geeks=20}
Is the key 'Welcomes' present? true
Is the key 'World' present? false
Note: The same operation can be performed with any type of variation and combination of different data types.