Saturday, May 23, 2026
HomeLanguagesJavaDictionary size() Method in Java with Examples

Dictionary size() Method in Java with Examples

The size() Method of Dictionary class in Java is used to know the size of the dictionary or the number of distinct keys present in the dictionary.

Syntax:

DICTIONARY.size()

Parameters:
The method does not accept any parameters.

Return Value:
The method returns the number of keys present in the dictionary.

Below programs illustrate the size() Method of Dictionary:
Program 1:




// Java Code to illustrate size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // Creating a dictionary of Hashtable
        Dictionary<Integer, String> dict
            = new Hashtable<Integer, String>();
  
        // Inserting elements into the Dictionary
        dict.put(10, "Geeks");
        dict.put(15, "4");
        dict.put(10, "Geeks");
        dict.put(25, "Welcomes");
        dict.put(30, "You");
  
        // Displaying the Dictionary
        System.out.println("Dictionary: " + dict);
  
        // Displaying the size of the dictionary
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}


Output:

Dictionary: {10=Geeks, 30=You, 15=4, 25=Welcomes}
The size of the dictionary is 4

Program 2:




// Java Code to illustrate size()
import java.util.*;
  
public class Dictionary_Demo {
    public static void main(String args[])
    {
  
        // Creating a dictionary of Hashtable
        Dictionary<String, Integer> dict
            = new Hashtable<String, Integer>();
  
        // Inserting elements into the table
        dict.put("Geek", 10);
        dict.put("4", 15);
        dict.put("Geeks", 20);
        dict.put("Welcomes", 25);
        dict.put("You", 30);
  
        // Displaying the Dictionary
        System.out.println("Dictionary: " + dict);
  
        // Displaying the size of the dictionary
        System.out.println("The size of the dictionary is "
                           + dict.size());
    }
}


Output:

Dictionary: {You=30, Welcomes=25, 4=15, Geeks=20, Geek=10}
The size of the dictionary is 5
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS