본문 바로가기

알면 좋은것

String은 참조형 변수인가?

아래의 결과를 예측할 수 있는가?

public class Main {
    public static void main(String[] args) {
        String a1 = new String();
        String a2 = a1;
        a1 = "hello";
        a2 = "hi";
        System.out.println(a1);
        System.out.println(a2);
    }
}
정답 : 
hello
hi

어 ? String은 참조타입이라고 들었는데 왜 Hello가 두번 안나오지?

기본형 타입과 참조 타입의 차이를 알고 있는가?
아래의 선언중 2개는 문제가 있다.

//1번
int s1 =  5;
int s2 = 10;

int ss1 = new int(5);
int ss2 = new int(10);
//2번
Integer s1 =  5;
Integer s2 = 10;

int ss1 = new Integer(5);
int ss2 = new Integer(10);
//3번
int s1 =  5;
int s2 = 10;

Integer ss1 = new int(5);
Integer ss2 = new int(10);

잘 모르겠으면 다음의 글을 참조하자.
박싱과 언박싱

정답은 1번과 3번이다

String은 엄밀히 따지면 참조타입이지만 기본형 타입도 가능하다

Java의 String은 2가지 방식으로 생성이 가능하다.


String s1 = "hello";
String s2 = "hello";

String ss1 = new String("hello");
String ss2 = new String("hello");

이때, 차이점은
String s1 = "hello"라고 선언한 s1과 s2는 ==을 통해 물어보면 true라 출력하고,
String ss1 = new String("hello")라고 선언한 ss1과 ss2는 ==을 통해 물어보면 false라 출력한다.

System.out.println("String Test");

String s1 = "hello";
String s2 = "hello";

String ss1 = new String("hello");
String ss2 = new String("hello");

System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(ss1 == ss2);
System.out.println(ss1.equals(ss2));
정답 :
true
true
false
true

더 자세한 내용이 알고싶다면 Java String Pool 참조

'알면 좋은것' 카테고리의 다른 글

Network 정리  (4) 2024.12.10
MultiThread 정리  (0) 2024.12.02
가장 좋은 최적화란 뭘까  (0) 2024.12.01
박싱과 언박싱  (0) 2024.04.13