Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda