Java

자바 프로그래밍 (Java) - 39 : 문자열 비교 메서드 equals (==와 equals의 차이)

n.han 2016. 7. 15. 16:27

 

2) 문자열 비교 메서드 equals ( == equals의 차이 )

 

  String 클래스는 문자열을 비교하는 메서드인 equals를 제공한다. equlas syntax는 다음과 같다.

 

str1.equals(str2)    // str1 str2의 문자열을 비교한다.

 

  이는 ==와 분명 차이가 있다. ==은 두 피연산자의 메모리 주소가 같은 지 판단하는 것 이기 때문이다.

 

  아래 예제는 == equals의 차이를 명확히 보여준다. str1 str2가 같은 메모리를 가리키고 있는 것을 볼 수 있다.

 

  이는 두 레퍼런스가 같은 문자열인 “Hello”를 가리키고 있기 때문이다.

 

  반면 str3 str4은 다른 메모리를 가리키고 있는 것을 볼 수 있다.

 

  이는 new 키워드를 통해서 String 객체를 생성했고 따라서 문자열 리터럴이 별도로 관리되기 때문이다.

 

public class Hello {

        public static void main(String[] args) {

               String str1 = "Hello";

               String str2 = "Hello";

               String str3 = new String("Java");

               String str4 = new String("Java");

               test(str1, str2);

               test(str3, str4);

        }  

    

        public static void test(String str1, String str2){

               if(str1 == str2)

                       System.out.println(" 객체는 같은 메모리를 가리킵니다.");

               else

                       System.out.println(" 객체는 다른 메모리를 가리킵니다.");

              

               if(str1.equals(str2))

                       System.out.println(" 객체는 같은 문자열을 가지고 있습니다.");

               else

                       System.out.println(" 객체는 다른 문자열을 가지고 있습니다.");

        }

}

출력 결과

두 객체는 같은 메모리를 가리킵니다.

두 객체는 같은 문자열을 가지고 있습니다.

두 객체는 다른 메모리를 가리킵니다.

두 객체는 같은 문자열을 가지고 있습니다.