# String을 생성하는 2가지 방법과 차이점

자바에서 String 객체 생성하는 방법 2가지

1. String literal : " " 사용 => 내용이 같다면 같은 객체! 동일한 메모리 주소를 갖는다!
2. new 연산자 사용 => 내용이 같더라도 개별적인 객체

흔히 new 연산자로 String 객체를 생성지 않는 것이 좋다는 말이 있다. 이 말을 이해해보자.\
String literal로 생성하면 해당 String 값은 Heap 영역 내 "Strinng Constant Pool"에 저장되어 재사용되지만, new 연산자로 생성하면 같은 내용이라도 여러 개의 객체가 Heap영역을 차지한다.

![String literal과 new를 사용한 String 차이점](/files/-Mclh_2_yaWmxiS9LSlt)

* String literal 로 생성한 객체는 String Pool에 들어간다.

* String literal 로 생성한 객체값(ex."Cat")이 이미 String Pool에 존재한다면 해당 객체는 String Pool의 reference를 참조한다!

* new 연산자로 생성 String 객체는 같은 값이 String Pool에 이미 존재하라도, Heap 영역 내에 별도 객체를 가리키게 된다.

* (참고) String 클래스의 intern( ) 메서드\
  해당 String과 동등한 String 객체가 이미 String Pool에 존재한다면 그 객체 그대로 리턴하고, 그렇지 않다면 호출된 String 객체를 StringPool에 추가하고 객체의 reference를 리턴한다.

```java
void internedString(){
    String constantString = "interned String";
    String newString = new String("interned String");
    String internedString = newString.intern();
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/java/reference/string-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
