Saturday, August 30, 2025
HomeLanguagesJavaInitialize a static map in Java with Examples

Initialize a static map in Java with Examples

In this article, a static map is created and initialized in Java.

A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.

  • Method 1:
    1. Creating a static map variable.
    2. Instantiating it in a static block.

    Below is the implementation of the above approach:




    // Java program to create a static map
      
    import java.util.*;
      
    class GFG {
      
        // Declaring the static map
        private static Map<Integer, String> map;
      
        // Instantiating the static map
        static
        {
            map = new HashMap<>();
            map.put(1, "GFG");
            map.put(2, "Geek");
            map.put(3, "GeeksForGeeks");
        }
      
        // Driver code
        public static void main(String[] args)
        {
            System.out.println(map);
        }
    }

    
    
    Output:

    {1=GFG, 2=Geek, 3=GeeksForGeeks}
    
  • Method 2: Creating a static map variable and instantiating it together.

    Below is the implementation of the above approach:




    // Java program to create a static map
      
    import java.util.*;
      
    class GFG {
      
        // Declaring the static map
        private static Map<Integer, String> map
            = new HashMap<>() {
                  map.put(1, "GFG");
                  map.put(2, "Geek");
                  map.put(3, "GeeksForGeeks");
              }
      
        // Driver code
        public static void main(String[] args)
        {
            System.out.println(map);
        }
    }

    
    
    Output:

    {1=GFG, 2=Geek, 3=GeeksForGeeks}
    
RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7014 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6702 POSTS0 COMMENTS