Dictionary put() Method in Java with Examples
Last Updated :
27 Dec, 2018
The put() method of Dictionary is used to insert a mapping into the dictionary. This means a specific key along with the value can be mapped into a particular dictionary.
Syntax:
DICTIONARY.put(key, value)
Parameters: The method takes two parameters, both are of the Object type of the Dictionary.
- key: This refers to the key element that needs to be inserted into the dictionary for mapping.
- value: This refers to the value that the above key would map into.
Return Value: The method returns the value to which the key is mapped. NULL is returned if the key is not mapped into any value.
Below programs are used to illustrate the working of java.util.Dictionary.put() Method:
Program 1:
import java.util.*;
public class Dictionary_Demo {
public static void main(String[] args)
{
Dictionary<Integer, String> dict
= new Hashtable<Integer, String>();
dict.put( 10 , "Geeks" );
dict.put( 15 , "4" );
dict.put( 20 , "Geeks" );
dict.put( 25 , "Welcomes" );
dict.put( 30 , "You" );
System.out.println( "Initial Dictionary is: " + dict);
String returned_value = (String)dict.put( 20 , "All" );
System.out.println( "Returned value is: " + returned_value);
System.out.println( "New Dictionary is: " + dict);
}
}
|
Output:
Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: Geeks
New Dictionary is: {10=Geeks, 20=All, 30=You, 15=4, 25=Welcomes}
Program 2:
import java.util.*;
public class Dictionary_Demo {
public static void main(String[] args)
{
Dictionary<Integer, String> dict
= new Hashtable<Integer, String>();
dict.put( 10 , "Geeks" );
dict.put( 15 , "4" );
dict.put( 20 , "Geeks" );
dict.put( 25 , "Welcomes" );
dict.put( 30 , "You" );
System.out.println( "Initial Dictionary is: " + dict);
String returned_value = (String)dict.put( 50 , "All" );
System.out.println( "Returned value is: " + returned_value);
System.out.println( "New Dictionary is: " + dict);
}
}
|
Output:
Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: null
New Dictionary is: {10=Geeks, 20=Geeks, 30=You, 50=All, 15=4, 25=Welcomes}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...