String 이란?
우리가 알고 있는 그 문자열 그 String 맞다
String의 메모리 관리
String의 메모리 관리란 String이 생성되고 만들어질 때 어떤 식으로 저장되는지에 대해 알아보는 것이다
일단 String의 사용법은 두 가지 있다
String str1 = "hello"; //문자열 리터럴 방식
Stirng str2 = new String("hello"); //객체 생성 방식
위의 두 코드를 비교해보자
String str1 = "hello"
String str2 = new String("hello")
System.out.println(" == : " + str1 == str2);
System.out.println("equals : " + str1.equals(str2));
//출력
== : false
equals : true
[ == ]으로 비교하면 False가 나오고 equals로 비교해보면 True가 나온다 어째서 이런 결과가 나온 것일 까?
결과의 이유
java에서는 문자열 리터럴을 사용하여 String을 생성할 시 Heap 메모리에 String Constant Pool이라는 곳에 저장합니다,
하지만 객체 생성을 할시에는 Heap 메모리에 저장되는 것이죠
그래서 [ == ]는 주소가 같은지 물어보는 것이기 때문에 False 간 나온 것이고 equals()는 값이 같은지를 물어보는 것이기에
True가 나오던 것이었습니다
심화 (1)
public class Main{
public static void main(String[] args) {
String one = "apple";
String two = new String("apple");
String three = two;
System.out.println(two == three);
}
}
//출력
True
Two와 Three는 같은 값을 참조한다.
심화 (2)
String one = "apple";
String two = new String("apple");
String three = two;
two = new String("hello"); //two의 값을 바꿔주면
System.out.println(three);
System.out.println(two == three);
//출력
apple
flase
two는 새 객체를 만들어 Heap에 저장하고 three는 two의 값인 apple을 저장하고 있다.
궁금점
심화(2)에서 three는 Heap에 저장된 것일까? 아니면 Heap > String Constant Pool 에 저장 된 것일 까?
String one = "apple";
String two = new String("apple");
String three = two;
two = new String("hello"); //two의 값을 바꿔주면
System.out.println(one == three); //만약 constant pool에 있다면 true 아니면 flase
System.out.println(three);
System.out.println(two == three);
//출력
flase
apple
flase
위 코드를 보면 알 수 있듯이 그냥 Heap 메모리에 객체로 생성된 것 같다.
'💻 Computer > 🦀 Java' 카테고리의 다른 글
[Java] Comparable<T> , Comparator<T> (0) | 2022.07.25 |
---|---|
[Java] Generic (0) | 2022.07.23 |
[Java] Arrays.asList()은 무엇인가 (0) | 2022.07.21 |
Java this 와 super (0) | 2022.07.17 |
(Java) 다형성 (0) | 2022.07.03 |