7. What is the difference between creating String as new() and literal?

toutbon·2024년 2월 24일
0

질문의 목적

  • 스트링 객체와 스트링값의 차이

Creating String Object

// 1 . using new keyword
String s1 = new String("Java");
String s2 = new String("Java");

// 2. string literal - String pool
String s3 = "Java";
String s4 = "Java";

String pool 영역

  • jdk 1.7 이전에는 String pool 이라는 메모리 영역이 일반적으로 객체가 생성되는 heap 메모리 영역과 별도로 존재했음.

  • jdk 1.7 이후에는 heap메모리 안에 String pool 이 존재함. heap 메모리 내에있는 특정 영역이라고 이해하면 쉬움

  • 기본적인 pooling 방식을 따르기 때문에 이미 기존에 같은 내용의 문자열이 존재하는 경우 새로운 객체를 생성하지 않고 생성되어 있는 객체를 재사용함.

  • 따라서 (위 그림 참조) s3, s4는 같은 주소값을 가리키게 됨

  • 비교 결과는 아래와 같다

s1 == s2 // false
s1.equals(s2) // true 
s3 == s4 // true 
s3.equals(s4) // true

== Operator

  • compare reference
  • 주소값이 같은지 확인

equals()

  • compare contents of String
  • 실제 문자열이 같은지 확인

Keyword

  • new() generates String objects in heap memory
  • String literal generates in String pool, reusable heap memory
  • ==operator compares String references
  • equals() method compares String contents
profile
뚜봉

0개의 댓글