Study/Book

기초 : String 클래스 인스턴스 생성

HongUniverse 2023. 3. 6. 22:12
반응형

1) new 키워드 없이 인스턴스를 만드는 경우 

String str1 = "hello";
String str2 = "hello";

- 문자열이 메모리 중 상수를 저장하는 영역에 저장된다. 

- str1과 str2는 같은 인스턴스를 참조한다.

 

2) new 키워드로 인스턴스를 만드는 경우 

String str1 = new String("hello");
String str2 = new String("hello");

- 인스턴스는 무조건 힙 메모리 영역에 새로 만드므로 str1과 str2는 서로 다른 인스턴스를 참조한다. 


package javaStudy;

public class StringExam {
    public static void main(String[] args) {
        String str1 = new String("Hello World");
        String str2 = new String("Hello World");

        if(str1 == str2){
            System.out.println("str1과 str2는 같은 레퍼런스입니다.");
        }else{
            System.out.println("str1과 str2는 다른 레퍼런스입니다.");

        }
    }
}

실행결과

str1과 str2는 다른 레퍼런스입니다.

참조형 변수는 변수를 저장하는 공간에 객체를 저장할 수 없고, 그 위치의 주소 값을 변수에 담는다. == 연산자는 변수를 저장하는 공간의 값만 비교한다. 두 String 객체는 다른 영역에 객체가 저장됐고, 그 객체의 저장 위치는 다르므로 == 연산자로 비교했을 때 다르다고 결과가 나온다.

 


package javaStudy;

public class StringExam {
    public static void main(String[] args) {
        String str1 = new String("Hello World");
        String str2 = new String("Hello World");

        if(str1.equals(str2)){
            System.out.println("str1과 str2는 같은 레퍼런스입니다.");
        }else{
            System.out.println("str1과 str2는 다른 레퍼런스입니다.");
        }
    }
}

실행결과

str1과 str2는 같은 레퍼런스입니다.

equals 메소드는 구현한 내용을 판단한다. 객체의 주소를 비교하지 않고, 객체의 내용을 비교한다. 


참고 서적 ) 모두의 자바 

반응형