I am trying to initialize HashMap with Enum Month. However, getting an error like: "Exception in thread "main" java.lang.ExceptionInInitializerError". Please let me know why I am getting this error. I am getting this in static main class method and for line ChatGroups.initializeMap();
package static_initialization;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class ChatGroups {
public static final Map<String, Month> months = new HashMap<String, Month>() {{
months.put("Jan", Month.January);
months.put("Feb", Month.February);
months.put("Mar", Month.March);
months.put("Apr", Month.April);
months.put("Jun", Month.June);
months.put("Jul", Month.July);
months.put("Aug", Month.August);
months.put("Sep", Month.September);
months.put("Oct", Month.October);
months.put("Nov", Month.November);
months.put("Dec", Month.December);
}};
public static void initializeMap() {
System.out.println();
}
}
package static_initialization;
public enum Month {
January(0),
February(1),
March(2),
April(3),
May(4),
June(5),
July(6),
August(7),
September(8),
October(9),
November(10),
December(11);
private int month;
Month(int i) {
month = i;
}
}
package static_initialization;
public class Main {
public static void main(String[] args) {
initializeMaps();
}
public static void initializeMaps() {
try {
ChatGroups.initializeMap();
} catch (Exception ex) {
System.out.println("Neelabh exception = " + ex);
}
}
}
Please find the stack trace
Exception in thread "main" java.lang.ExceptionInInitializerError
at static_initialization.Main.initializeMaps(Main.java:10)
at static_initialization.Main.main(Main.java:5)
Caused by: java.lang.NullPointerException
at static_initialization.ChatGroups$1.<init>(ChatGroups.java:9)
at static_initialization.ChatGroups.<clinit>(ChatGroups.java:8)
putinstead ofmonths.putin the static initializerthis.putinstead ofmonths.put.monthspointer is not bound to the map object you are defining yet. So it's still null when that code runs.