Kinda a curiosity question, when I'm writing a program in java that looks kinda like this:
public class Basic {
public static HashMap<String,Integer> my_map = new HashMap<>();
public static void main(String[] a) {
mymap.forEach( (str,i) -> System.out.println(str+": "+i) );
}
}
essentially a structure to hold and process some static/global data, and then say for example (for code cleaness) I my values in a different class in a different file that would load all of the values into that main class upon init like this:
public class Foo {
static final String a = def("APPLE");
static final String b = def("BUMBLEBEE");
static final String c = def("CARTOGRAPHER");
static String def (String s) {
Basic.my_map.put(s, new Random().nextInt(256));
return s;
}
}
now in order for this code to function correctly (ie upon the program being launched all of the values defined in Foo get printed out) my instinct is to define an empty function inside of Foo and call it right at the start of main,
and I was basically wondering if this was actually necessary. Will all static variables get innited before the program starts or atleast before any code they impact is used. Or is it always best to manually make sure a class has been loaded before interacting with the data it might have interacted with.
A class is loaded when accessed, even to read just one static field of it, then all its static fields will be initialized (to null if unassigned) then any static block will run.
So when your "populating" class access the name of the class needs to be "populated", it causes it to load.
In your example, nothing calls/refers to "Foo". Assuming you just run the main method of Basic, then it should run empty.