1. Introduction

In Java, the HashMap class allows you to store key-value pairs. One essential method provided by the HashMap class is containsKey(). This method is used to check whether a particular key is being mapped into the HashMap or not. It returns true if the specified key is found in the map, otherwise false.

2. Program Steps

1. Create a HashMap object and populate it with some key-value pairs.

2. Use the containsKey() method to check if a specific key is present in the HashMap.

3. Print the result of the containsKey() method.

3. Code Program

import java.util.HashMap;

public class HashMapContainsKey {

    public static void main(String[] args) {

        // Step 1: Create a HashMap object and populate it with some key-value pairs
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Banana", 20);
        map.put("Cherry", 30);

        // Step 2: Use the containsKey() method to check if a specific key is present in the HashMap
        boolean containsBanana = map.containsKey("Banana");
        boolean containsGrapes = map.containsKey("Grapes");

        // Step 3: Print the result of the containsKey() method
        System.out.println("Contains key &apos;Banana&apos;: " + containsBanana);
        System.out.println("Contains key &apos;Grapes&apos;: " + containsGrapes);
    }
}

Output:

Contains key 'Banana': true
Contains key 'Grapes': false

4. Step By Step Explanation

Step 1: A HashMap object named map is created, and it is populated with three key-value pairs: "Apple" with value 10, "Banana" with value 20, and "Cherry" with value 30.

Step 2: The containsKey() method is used to check whether the HashMap contains the keys "Banana" and "Grapes". The method returns true for "Banana" and false for "Grapes" as "Grapes" is not a key in the HashMap.

Step 3: The results are printed, showing that the key "Banana" is present in the HashMap while the key "Grapes" is not.