자바에서 String 문자열 생성 방식

1. new String()

2. String literal("") 

 

두 개 차이 : 저장공간(메모리)의 차이

new 연산자를 사용하여 String을 생성할 경우

Heap 메모리 영역에 저장됨

 

리터럴(literal) 을 사용하여 String을 생성할 경우

Heap 안에 있는 String constant pool 영역에 생성

 

 

 

 

String s1 = "Cat";
String s2 = "Cat";
String s3 = new String("Cat");
  • literal로 생성한 s1, s2는 동일한 객체를 바라보고, new String()으로 생성한 s1은 다른 메모리 주소의 객체를 바라본다
  • String literal로 생성한 객체가 이미 존재한다면, 해당 객체는 이미 생성되어 있는 String constant pool 영역을 참조한다
  • new 연사자로 생성한 String 객체는 같은 값이 String pool에 존재하더라도, Heap영역에 별도로 객체를 생성한다.

 

System.out.println(s1.equals(s3)); //true 
System.out.println(s1 == s2);	//true
System.out.println(s1 == s3);	//false

 

  • equals값이 동일한지 비교하고, ==메모리상 동일한 객체인지 비교한다
  • s1과 s3는 값은 동일하지만 메모리상 저장된 곳이 다르기 때문에 false가 나온다
  • s1과 s2는 모두  literal을 사용한 동일한 문자열이기 때문에 동일한 주소값을 바라보므로 true가 나온다

 

 

참조 : https://yeoonjae.tistory.com/entry/Java-String-literal-%EA%B3%BC-new-String-%EC%9D%98-%EC%B0%A8%EC%9D%B4

'java > 공부' 카테고리의 다른 글

[JAVA] String, StringBuffer, StringBuilder 차이  (0) 2024.01.31
[JAVA] static 변수와 static 메소드  (0) 2024.01.31

+ Recent posts