본문 바로가기
전산 관련 시험/프로그래밍(C, JAVA, Python)

[JAVA] 프로그래밍 언어 (23.02 14)

by 응_비 2024. 10. 6.
public class Test {
    public static void main(String[] args) {
        String str1 = "Programming";
        String str2 = "Programming";
        String str3 = new String("Programming");

        System.out.println(str1 == str2);
        System.out.println(str1 == str3);
        System.out.println(str1.equals(str3));
        System.out.println(str2.equals(str3));
    }
}

 
해설:

  1. str1 == str2는 참(true)입니다. 같은 리터럴이기 때문에 같은 메모리 주소를 참조합니다.
  2. str1 == str3는 거짓(false)입니다. new 키워드를 사용하여 다른 메모리 주소에 저장되었기 때문입니다.
  3. str1.equals(str3)는 참(true)입니다. equals()는 문자열의 내용만을 비교합니다.
  4. str2.equals(str3)도 참(true)입니다.

출력 결과:

 
arduino

true
false
true
true

Java에서 ==와 equals의 차이점

   •   == 연산자는 두 문자열 객체가 **동일한 참조(메모리 위치)**를 가리키는지를 비교합니다.
   •   equals() 메서드는 두 문자열의 내용이 동일한지를 비교합니다.

댓글