Dictionary put(K, V) in Java

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

Syntax:

Integer java.util.Dictionary.put(K key, V value)

This method takes two arguments. This method maps the specified key to the specified value in this dictionary. Neither the key nor the value can be null.

Note:

1. If this dictionary already contains an entry for the specified key, the value already in this dictionary for that key is returned, after modifying the entry to contain the new element.

2. If this dictionary does not already have an entry for the specified key, an entry is created for the specified key and value, and null is returned.

Parameters: One parameter is required for this method.

key: the hashtable key.

value: the value.

Returns: the previous value to which the key was mapped in this dictionary, or null if the key did not have a previous mapping.

Throws:

NullPointerException - if the key or value is null.

Approach 1: When no exception

Java

import java.util.Dictionary;
import java.util.Hashtable;

public class Dictionaryput {
    public static void main(String[] args) {

        Dictionary<String, Integer> dictionary =
new Hashtable<String, Integer>();

        dictionary.put("Hello", 10);
        dictionary.put("Java", 4);
        dictionary.put("C++", 17);

        System.out.println(dictionary);

    }
}

Output:

{Java=4, C++=17, Hello=10}


Approach 2: NullPointerException

Java

import java.util.Dictionary;
import java.util.Hashtable;

public class Dictionaryput {
    public static void main(String[] args) {

        Dictionary<String, Integer> dictionary =
new Hashtable<String, Integer>();

        dictionary.put("Hello", null);

        System.out.println(dictionary);

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Hashtable.put(Hashtable.java:476)


No comments:

Post a Comment