
static 메서드는 Java 애플리케이션이 로드될 때 바로 로드되지 않습니다. 대신, static 메서드는 클래스가 처음으로 사용될 때 메모리에 로드됩니다. 다음은 이 동작에 대한 자세한 설명입니다:
클래스가 처음으로 사용될 때 JVM은 해당 클래스를 로드합니다. 클래스 로딩은 클래스 파일을 읽고 JVM 내부의 데이터 구조로 변환하는 과정입니다. 이 단계에서는 static 메서드와 static 변수의 메타데이터가 로드됩니다.
클래스가 로드된 후, 클래스 초기화 단계가 시작됩니다. 이 단계에서 static 블록과 static 변수 초기화가 실행됩니다. 이 시점까지는 static 메서드가 메모리에 로드되지만, 실제로 메서드가 호출되기 전까지는 실행되지 않습니다.
public class StaticExample {
// static 변수
private static int staticVar = initializeStaticVar();
// static 블록
static {
System.out.println("Static block executed");
}
// static 메서드
public static void staticMethod() {
System.out.println("Static method called");
}
// static 변수 초기화 메서드
private static int initializeStaticVar() {
System.out.println("Static variable initialized");
return 42;
}
public static void main(String[] args) {
System.out.println("Main method started");
StaticExample.staticMethod();
}
}
Static variable initialized
Static block executed
Main method started
Static method called
클래스 로딩:
StaticExample 클래스가 처음으로 사용될 때 (즉, main 메서드가 실행될 때), JVM은 StaticExample 클래스를 로드합니다.
클래스 초기화:
static 변수 초기화: staticVar 변수가 초기화되며, initializeStaticVar() 메서드가 호출됩니다. 이로 인해 "Static variable initialized"가 출력됩니다.
static 블록 실행: static 블록이 실행되며, "Static block executed"가 출력됩니다.
메인 메서드 실행:
"Main method started"가 출력됩니다.
StaticExample.staticMethod()가 호출되며, "Static method called"가 출력됩니다.
static 메서드는 클래스가 처음 로드되고 초기화될 때 메모리에 로드되지만, 실제 메서드 호출은 클래스가 로드된 후에야 이루어집니다. 이는 static 메서드가 클래스 로딩 시점에 바로 실행되는 것이 아니라, 해당 메서드가 호출될 때 실행됨을 의미합니다.