String str = "hello";
의 경우 "hello"
는 JVM의 문자열 상수 풀(String Constant Pool)에 저장됩니다.
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); // true (같은 객체를 참조)
"hello"
는 상수 풀에 저장됩니다.str1
과 str2
는 모두 같은 "hello"
를 참조합니다.new String("hello")
와의 차이점String str3 = new String("hello");
System.out.println(str1 == str3); // false (다른 객체를 참조)
new String("hello")
를 사용하면 항상 새로운 객체가 힙(Heap) 메모리에 생성됩니다.==
비교 결과가 false
가 됩니다."hello"
는 문자열 상수 풀(String Constant Pool)에 저장됩니다.new String()
은 상수 풀을 사용하지 않고 힙에 새로운 객체를 생성합니다.추가 학습 자료