[자바] 스트링 리터럴 vs 객체

김기연·2022년 2월 21일
0

자바

목록 보기
1/1

자바에는 스트링을 선언하는 방법이 두 가지가 있습니다.
하나는 리터럴, 하나는 객체로 선언할 수 있습니다.


아래와 같은 변수가 있다고 해보겠습니다.

//리터럴
String a = "hello";
String b = "hello";

//객체
String c = new String("hello");
String d = new String("hello");

리터럴


System.out.println(a.equals(b)); 
System.out.println(a==b); 

/*
true
true
*/

Java의 Heap 영역 안에 있는 String Constant Pool에 위치합니다.
String Constant Pool에 이미 존재하는 문자열이라면 같은 주소값을 공유합니다.
따라서 변수 a,b는 비교하였을 때, 문자열과 주소값이 모두 같은 것을 확인할 수 있습니다.

객체

System.out.println(c.equals(d)); 
System.out.println(c==d); 

/*
true
false
*/

Java의 Heap 영역에 할당됩니다.
새로운 인스턴스를 생성할 때마다 Heap 영역에 객체가 새로 생긴다.
따라서 변수 c,d를 비교하였을 때 문자열은 같지만 Heap 영역에서 서로 다른 객체로 생성되었기 때문에 주소값은 다릅니다.

리터럴 vs 객체

System.out.println(a.equals(c)); 
System.out.println(a==c); 

/*
true
false
*/

스트링 리터럴은 String Constant Pool 영역에, 객체는 Heap 영역안에 위치하므로
변수 a,c는 서로 다른 주소값을 참조합니다.

intern()

intern() 메서드는 String Constant pool에서 리터럴 문자열이 있으면 반환하고, 없다면 새로 문자열을 넣어주고 그 주소값을 반환합니다.


System.out.println(a==c.intern()); 

/*
true
*/

new연산자로 생성한 변수 c에 intern 메서드를 적용하면 리터럴 변수인 a와 참조하는 주소값이 같아집니다.
1. intern() 메소드 실행
2. String Constant Pool에 문자열 존재하는지 확인
3. 동일한 주소값 리턴

intern
public String intern()
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The JavaLanguage Specification.

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

출처: 자바 공식문서

💡String Constant Pool 이란?

자바 메모리 중 Heap 영역 안에 위치하여 스트링을 별도로 관리하는 장소입니다.
Heap 안에 있기 때문에 모든 스레드가 공유할 수 있고 가비지 콜렉터의 대상이 됩니다.

참고

자바의 String 객체와 String 리터럴
String.intern() 이란? 언제 사용하는가?

0개의 댓글