❓ java에서는 new 예약어가 아닌 literal 방식으로 String을 생성하는 이유?

https://www.javatpoint.com/java-string
literal방식으로 String 생성하는 경우 JVM은 stirng constatnt pool을 먼저 체크한다. String객체가 이미 존재한다면, String 인스턴스 참조값이 리턴된다. String 객체가 존재하지 않는다면 String 인스턴스를 constant pool에 생성한다.
자바는 메모리 오버헤드를 줄이기 위해위와 같은 방식을 사용한다.
memory overhead
String contant pool(String Intern Pool이라고도 한다)
String test = “welcom”이 String constant pool에 객체가 생성되고, 참조값은 stack영역에 저장된다.
아래 코드를 통해 동일한 String 리터럴값에 대해 주소값이 똑같은것을 확인 할 수 있다.
public class ProfilePrint {
public static void main(String[] args) {
String s1 = "HelloWorld";
String s2 = "HelloWorld";
String s3 = "Greeting";
String s4 = new String("Greeting");
String s5 = "HelloWorld";
if(s1 == s2) {
System.out.println("s1 s2 same instance");
}
if(s3 == s4) {
System.out.println("s3 s4 same instance");
} else {
System.out.println("s3 s4 NOT same instance");
}
}
}
s1 s2 same instance
s3 s4 NOT same instance
String이 immutable하기 때문에 heap space를 많이 차지하는데 String pool을 통해 공간 java heap 공간을 절약할 수 있다.
(String을 immutable하게 설계해서 효율적으로 사용하기 위해 String contant pool이 생긴거 같다.)
String constant Pool은 HashMap을 사용한다.
hashMap의 동일한 버킷에는 동일한 hashcode의 String값이 존재한다.
예전 버전 자바에서는 고정된 사이즈의 pool을 사용하여 “Could not reserve enough space for object heap” 에러를 자주 보았다고 한다.
JDK7에서는 constant pool이 permgen space영역에 있었는데, JDK8 main heap 메모리 영역으로 편입되었다.
JAVA 동작방식정리
| 연사자 종류 | 수행하는 연산 |
|---|---|
| + | 덧셈 |
| - | 뺄셈 |
| * | 곱하기 |
| / | 나누기 (몫) |
| % | 나누기(나머지) |
| 연산자 종류 | 수행하는 연산 |
|---|---|
| += | 기존값에 우측항의 값을 더함 |
| -= | 기존값에 우측항의 값을 뺌 |
| *= | 기존값에 우측항의 값을 곱함 |
| /= | 기존값에 우측항의 값으로 나눔 |
| %= | 기존값에 우측항의 값으로 나눈 나머지 |
public class Increment {
public static void main(String[] args) {
Increment increment = new Increment();
increment.increment();
}
public void increment() {
int intValue = 1;
System.out.println(intValue++);//1
System.out.println(intValue);//2
System.out.println(++intValue);//3
System.out.println(intValue);//3
}
}
| 연산자 종류 | 수행하는 연산 |
|---|---|
| + | 변수 * 1 |
| - | 변수 * (-1) |
| ++ | 변수 1만큼 증가 |
| — | 변수 1만큼 감소 |
| ! | boolean 타입에서만 사용 가능. true, false의 결과를 반대로 뒤집는다. |
단항 연산자
산술 연산자
1. 2순위 ) *, /, %
2. 3순위 ) +,-
[참고]
Overhead (computing)
Where Does Java’s String Constant Pool Live, the Heap or the Stack? | Baeldung