[Java] 문자열 비교 - ==과 equals()

C____JIN·2022년 10월 17일
0

Java

목록 보기
7/9
post-thumbnail

String 변수 생성

String str1 = "apple"; //리터럴을 이용한 방식
String str2 = "apple"; //리터럴을 이용한 방식
String str3 = new String("example"); //new 연산자를 이용한 방식
String str4 = new String("example"); //new 연산자를 이용한 방식

리터럴을 이용한 방식

  • string constant pool이라는 영역에 생성
    • intern() 메서드가 호출됨
      • intern() : 주어진 문자열이 string constant pool에 존재하는지 검색해서 존재하면 주소를 반환

new 연산자를 이용한 방식

  • Heap 영역에 생성

문자열 비교

== 연산자

  • 비교하고자 하는 대상의 주소값을 비교

    public class compare {
        public static void main(String[] args) {
            String s1 = "apple";
            String s2 = new String("apple");
    
            if(s1 == s2) {
                System.out.println("일치");
            }else {
                System.out.println("불일치");
            }
        }
    }
    • 불일치

equals()

  • 비교하고자 하는 대상의 값 자체를 비교

    public class compare {
        public static void main(String[] args) {
            String s1 = "apple";
            String s2 = new String("apple");
    
            if(s1.equals(s2)) {
                System.out.println("일치");
            }else {
                System.out.println("불일치");
            }
        }
    }
    • 일치

마무리

equals()와 == 연산자의 차이를 잘 몰라서 알고리즘을 푸는데, 계속 맞왜틀을 하고 있었다. 이번 기회에 주소값비교와 단순 값 비교라는 차이점을 알게되었으니 같은 실수는 반복하지 말자!

profile
개발 블로그🌐 개발일지💻

2개의 댓글

comment-user-thumbnail
2022년 10월 17일

오 저도 도움이 많이 되네요! 퍼가요~(하트)

답글 달기
comment-user-thumbnail
2022년 10월 20일

이거 진짜 찐도움이네여...

답글 달기