Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda