get(Object): This method is available in java.util.Hashtable class of Java.
Syntax:
V java.util.Hashtable.get(Object key)
This method takes one argument. This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Parameters: One parameter is required for this method.
key: the key whose associated value is to be returned.
Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Throws:
NullPointerException - if the specified key is null.
Approach 1: When no exception
Java
import java.util.Hashtable;public class Hashtableget {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);Object key = "Hello";System.out.println(hashtable.get(key));}}
Output:
1
Approach 2: NullPointerException
Java
import java.util.Hashtable;public class Hashtableget {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);Object key = null;System.out.println(hashtable.get(key));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null at java.base/java.util.Hashtable.get(Hashtable.java:381)
No comments:
Post a Comment