본문 바로가기
JAVA

[Java] 자바에서 클래스는 언제 로딩이 되는가

by Rainbound-IT 2023. 10. 17.
반응형

 

 

자바에서 클래스 변수, 인스턴스 변수, 지역변수 이렇게 있다고 하는데

클래스 변수 빼고는 선언 할때 올라가는게 보이는데

 

클래스변수의 경우는 선언 안하고 사용하기 때문에 순서가 궁금해졌다.

 

 

 

 

메인 메소드가 올라가고 바로 올라간뒤 스태틱 블록이 올라간다.

 

예를 들어 다음 코드를 실행해 보면 된다.

 

// Java Program to illustrate static block concept 
// alongside discussing the class loading 

// Importing all input output classes 
import java.io.*; 

// Class 
class main { 

	// Static block 
	static
	{ 
		// Static block will be executed first 
		// before anything else 

		// Print message 
		System.out.println( 
			"I am static block and will be shown to eyeballs first no matter what"); 
	} 

	// Main driver method 
	public static void main(String[] args) 
	{ 
		// Print message 
		// Now main method will execute 
		System.out.println( 
			"I am the only line in main method but static block is hindering me to display first"); 
	} 
}

 

실행해보면 static 이 먼저 나오게 된다.

main 메소드는 먼저 로딩이 되나 메인메소드 내에 있는 것보다 class 함수가 먼저 로딩 되어 출력되는 것을 볼수 있다.

 

 

 

 

Reference

https://www.geeksforgeeks.org/what-is-class-loading-and-static-blocks-in-java/

 

What is Class Loading and Static Blocks in Java? - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

 

반응형

댓글