Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
Do I have to make sure classes are loaded manually in Java before I use data they affect?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!