Hashtable put(K, V) in Java

put(K, V): This method is available in java.util.Hashtable class of Java.

Syntax:

V java.util.Hashtable.put(K key, V value)

This method takes two arguments. This method maps the specified key to the specified value in this hashtable.

Note: Neither the key nor the value can be null.

Parameters: Two parameters are required for this method.

key: the hashtable key.

value: the value.

Returns: the previous value of the specified key in this hashtable, or null if it did not have one.

Throws:

NullPointerException - if the key or value is null

Approach 1: When no exception

Java

import java.util.Hashtable;

public class Hashtableput {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable =
new Hashtable<String, Integer>();

        hashtable.put("Hello", 1);
        hashtable.put("World", 2);

        System.out.println(hashtable);

    }
}

Output:

{World=2, Hello=1}


Approach 2: NullPointerException

Java

import java.util.Hashtable;

public class Hashtableput {
    public static void main(String[] args) {
        Hashtable<String, Integer> hashtable =
new Hashtable<String, Integer>();

        hashtable.put("Hello", 1);
        hashtable.put(null, 2);

        System.out.println(hashtable);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null at java.base/java.util.Hashtable.put(Hashtable.java:481)


No comments:

Post a Comment