Immutable
그럼 이 차이점을 두고 간단한 테스트를 한번 해보자
ex)
String str = "안녕";
String string = new String("안녕");
System.out.println("Literal 안녕 삽입 후, str address: " + str.hashCode());
System.out.println("New안녕 삽입 후, string address: " + string.hashCode());
System.out.println("두 문자열 비교: " + str == string);
str += "NHN";
System.out.println("NHN 삽입 후, str address: " + str.hashCode());
[결과]
Literal 안녕 삽입 후, str address: 1277839209
New 안녕 삽입 후, string address: 2930001123
두 문자열 비교: false
NHN 삽입 후, str address: 3755200
Q. 왜 두 문자열은 같은데 비교 시 false 를 반환할까?
A. String type 의 값 할당 방식에 따라 저장 방식이 다르기 때문이다.
Mutable
ex)
StringBuilder builder = new StringBuilder();
StringBuffer buffer = new StringBuffer();
builder.append("빌더");
buffer.append("버퍼");
System.out.println("빌더 삽입 후, builder address: " + builder.hashCode());
System.out.println("버퍼 삽입 후, buffer address: " + buffer.hashCode());
builder.append("NHN");
buffer.append("NHN");
System.out.println("스트링 삽입 후, builder address: " + builder.hashCode());
System.out.println("스트링 삽입 후, buffer address: " + buffer.hashCode());
[결과]
빌더 삽입 후, builder address: 1925478856
NHN 삽입 후, builder address: 1925478856
버퍼 삽입 후, buffer address: 434171759
NHN 삽입 후, buffer address: 434171759
public AbstractStringBuilder append(String str) {
if (str == null) {
return appendNull();
}
int len = str.length();
ensureCapacityInternal(count + len);
putStringAt(count, str);
count += len;
return this;
}
(출처 - tuandevnotes.com)