JAVA

[ java ]Constant Pool과 String Constant Pool

Adose 2024. 12. 10. 13:19

📌 Constant Pool


  • JVM의 Method Area 내부에 위치하고 있다.
  • Constant Pool은 클래스를 컴파일할때 생성된다.
    • 컴파일 될때, 클래스 파일내에 포함된 클래스의 구성요소(상수, 문자열, 클래스)를 저장하고 관리한다.
    • Constant Pool에 저장된 값들은 런타임 시점에 JVM에 의해 사용된다.

 

 

📌 String Constant Pool

String Constant Pool 또는 String Pool이라고 부른다.


  • JVM의 heap 내부에 위치하고 있다.
    • String Constant Pool은 Heap 영역 안에서 관리된다.
  • 런타임시점에 사용되는 메모리 영역이다.
String test1 = "hello";
String test2 = "hello";
  • 리터럴 사용시 String Constant Pool(=String pool) 동작 과정
  1. hello 는 heap영역 내부에 있는 StringtPool에 저장이 되고, test1 변수는 스택에 저장된다.
  2. 이때 test1 에서 hello를 StringPool에 저장했기 때문에, test2 는 StringPool에 이미 만들어진 hello 를 참조하게 된다.
  3. test1 변수는 stack에 저장되게 된다.
  4. 이 이유로 → test1 == test2 // true 가 나오게 된다.

 

String test1 = new String("hello");
String test2 = new String("hello") 
  • new 사용시 동작 과정
  1. 각각 하나의 객체로서 heap에 저장되게 된다
  2. 이때 hello는 객체이기 때문에, StringPool에 저장되지 않는다.
  3. heap에 객체로서 각각 hello, hello가 저장되게 되고
  4. 스택에 test1 과 test2 변수(각각의 hello를 가리킨다)가 저장된다.
  5. 이 이유로 test1 == test // false가 나오게 된다.

 

 

📌 결론

  • Constant pool : 컴파일 시점에 사용되며, 클래스 파일에 포함된 상수 들을 저장한다.
  • String pool : 런타임 시점에 JVM에 의해 활용되며, String 리터럴 값을 저장 또는 재사용한다.
String str1  = "test";
String str2 = new String("test");
String str3 = new String("test");
String str4  = "test";

System.out.println(str1 == str4);
System.out.println(str1 == str2);
System.out.println(str1 == str3);
System.out.println(str2 == str3);
  • 결과 
    • str1 값은 String pool에 저장되고, 재사용된다.
    • str2 값은 힙에 저장되며, 재사용되지 않고 객체로서 각각 만들어진다.

 

 

❓ 컴파일 ?

  • 소스코드가 컴파일러에 의해 바이트 코드로 변환되는 과정
  • 문법 검사, 타입 검사 등
  • Ex java → class

❓런타임 ?

  • 프로그램이 실행되는 시점
  • 실제 프로그램 실행, 메서드 호출, 메모리 할당 등

 

 

참고 블로그


https://rlaehddnd0422.tistory.com/184

https://deveric.tistory.com/123