String 과 new String

MSKim·2023년 2월 27일
0

Java

목록 보기
8/19
public class Main {
    public static void main(String[] args) {
        String str1 = new String("Hello");
        String str2 = "Hello";
        String str3 = "Hello";
        
        System.out.println(str1.equals(str2));   // true
		System.out.println(str1 == str2);        // false
		System.out.println(str2 == str3);        // true
    }
}

두 가지 방식 모두 String 객체를 생성한다는 사실은 같지만 가장 큰 차이점은 JVM이 관리하는 메모리 구조상에서 명백히 다르다.

String은 불변한다는 특징을 가지고 있다.
String 객체들의 연산이 이루어지면, 새로운 객체를 계속 만들어내기 때문에 메모리 관리 측면에서 상당히 비효율적이다.
이러한 이유로 만들어진 메모리 영역이 Heap 안에 있는 String Constant Pool이다.

불변객체의 특징 때문에 String 객체는 개발자가 생각하는 것 이상을 ㅗ만들어지기 때문에 특정한 공간에 두고 재활용하기 위해 String constant pool이 존재하고 이런 방식을 Interning이라고 한다.

여기에는 기존에 만들어진 문자열 값이 저장되어 있고, str2 와 str3처럼 리터럴로 생성된 같은 값을 가지는 객체는 같은 레퍼런스를 가지게 된다.

str1은 heap 메모리에 개별 객체가 만들어지고, str2 와 str3 은 String Constant Pool에 만들어진 하나의 객체를 참조한다.
따라서 총 2개의 String 객체가 생성된다.

profile
Today I Learned

0개의 댓글