본문 바로가기

공부 정리

equals vs == (string pool)

반응형

목차


1. String pool이란?
2. 예제
2. String 불변의 법칙
3. intern()의 구현

 

1. String Pool이란?


 String Pool은 자바에서 생성되는 문자열 리터럴들이 저장되는 공간이며 JVM의 heap에 위치합니다. String 불변(immutable)의 법칙과 intern()의 구현을 컨셉으로 합니다. 처음에는 빈 공간으로 초기화되며, String이 생성될 때마다 추가됩니다.

 

 

  • String Pool의 장점

1. 스트링 풀은 스트링 객체를 캐싱합니다. 다른 객체에 의해 사용되므로 JVM의 많은 메모리 공간을 절약합니다.

 

2. 스트링 풀은 재사용성 때문에 어플리케이션의 성능에 도움을 줍니다. 같은 값이 이미 스트링 풀에 존재한다면, 새로운 스트링 생성하는 시간을 절약합니다.

 

 

2. 예제


String pool

 

 

new를 사용해서 String 객체를 만드는 경우, 해당 문자열을 가리키는 객체가 Heap 메모리에 올라갑니다.

 

String pool

 

 

s3.intern() 메서드를 실행하면, 스트링 풀에 "Hi" 값을 가지는 스트링이 있는지 검사합니다. 스트링 풀에는 이미 "Hi" 문자열이 있기 때문에, 스트링 풀에 있는 참조를 반환하고 s3에 할당됩니다.

 

 

코드로 표현하면 아래와 같습니다.

 

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		String s1 = "apple";
		String s2 = "banana";
		String s3 = new String("cyber");
		String s4 = new String("apple");
		String s5 = s3+s3;
		String s6 = "apple";
		
		System.out.println(s1==s4); //false
		System.out.println(s1.equals(s4)); //true
		System.out.println(s1==s6); //true
	}
}

 

 

String은 2가지 방식으로 만들 수 있습니다.

 

  • " " 사용
  • new String(String s) 사용

 

s1,s2,s5는 1번을 사용했고 s3,s4는 2번을 사용했습니다.

 

 1번을 이용하든지 2번을 이용하던지 먼저 확인 할 것은 해당 문자열이 String pool에 있는가 확인하는 것입니다. 단순히 변수로 선언된 1번의 경우, 각 변수는 String pool에 있는 문자열을 가리킵니다.

 

 객체로 만들어진 2번의 경우, 각 객체는 해당 문자열이 String pool에 문자열이 있는지 확인합니다. String pool에 없으면 등록합니다.(s3의 1번) 그 이후 자신의 객체를 heap 영역에 생성합니다.(s3의 2번) 이 과정은 내부적으로 intern()이 작동되기 때문에 가능합니다.

 

 

3. String 불변의 법칙


먼저 String s3를 생성해봅시다.

 

String s3 = new String("cyber");

 

다음을 해보면 어떻게 될까요?

 

s3=s3+s3;

 

 기존에 생성해 두었던 s3에 "cybercyber"가 저장되지 않고 String pool에 "cybercyber"가 새롭게 만들어집니다. 이건 String 불변의 법칙 때문인데, 한 번 만들어진 String은 변경이 불가능하기 때문입니다.

 

 

4. intern()의 구현


public String intern()

 

 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 Java™ Language Specification.

 

 String class에 의해 JVM 내부의 heap에는 비어있는 String pool이 생성됩니다. intern() 메소드가 실행될 때, 만약에 스트링 풀에 equals(Object) 메서드에 의해 결정된 스트링 객체와 동일한 문자열을 가지고 있다면, 스트링 풀에 있는 해당 문자열을 반환합니다. 문자열이 존재하지 않는다면 일단 String pool에 등록하고 문자열을 반환합니다. 

 

 

* 출처


https://www.javastring.net/java/string/pool

반응형

'공부 정리' 카테고리의 다른 글

다형성 / Up-casting & Down-casting  (0) 2020.07.20
Wrapper class / Integer cache pool  (0) 2020.07.17
Override vs Overload  (0) 2020.07.17
Java Heap vs Stack (Memory Allocation)  (0) 2020.07.15
JDK, JRE  (0) 2020.07.14