Answer the question
In order to leave comments, you need to log in
When a class is initialized, are its instace members loaded into memory?
When a class is initialized (for example, when we access its static fields for the first time, without creating an object), are its instace members loaded into memory? Or is there only static members in RAM?
Answer the question
In order to leave comments, you need to log in
They may load or they may not. JVMS does not specify whether all, some, or none of the types referenced by the class being loaded should be loaded. So this behavior is at the discretion of the JVM developer.
HotSpot, for example, implements lazy class loading. That is, it does not load classes unless it is strictly necessary. It may not even load all static members during class static initialization.
Example:
import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
public class A {
private static LocalDateTime ldt;
private static CountDownLatch cdl;
static {
ldt = LocalDateTime.now();
cdl = null;
}
public static void main(String[] args) {
System.out.println("123");
}
}
...
[0,100s][info][class,load] java.time.temporal.TemporalAccessor source: shared objects file
[0,100s][info][class,load] java.time.temporal.Temporal source: shared objects file
[0,100s][info][class,load] java.time.temporal.TemporalAdjuster source: shared objects file
[0,101s][info][class,load] java.time.chrono.ChronoLocalDateTime source: shared objects file
[0,101s][info][class,load] java.time.LocalDateTime source: shared objects file
...
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class A {
public static void main(String[] args) {
if ("world".equals(System.getenv("HELLO"))) {
System.out.println(LocalDateTime.now());
} else {
System.out.println(BigDecimal.TEN);
}
}
}
public class Person {
static FullName staticFullName;
FullName fullName;
int age;
}
public class FullName {
String name;
String surname;
}
public class Test {
public static void main(String[] args) {
Person person = new Person();
System.out.println("This is age " + person.age);
System.out.println("This is fullName " + person.fullName);
System.out.println("This is static fullName " + Person.staticFullName);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question