String 문자열 비교 == vs equals()

choijh·2022년 10월 27일

Java+Jsp

목록 보기
5/12

문자열 비교 == vs equals()

  • equals()는 Object에 정의되어있는 메소드다.

  • compareTo()를 통해서도 문자열을 비교 가능하다. equals()와 다르게 사전적 순서를 기준하여 리턴해준다.
    1. 0: 두개의 문자열 동일
    2. 양수: 호출객체가 사전적 순서가 인자보다 앞에 있을 때
    3. 음수: 인자가 객체보다 순서가 앞설 때


String s1 = "abc";
String s2 = "abc";
String str1 = new String("abc");
String str2 = new String("abc");

System.out.println(s1.equals(s2)); // true
System.out.println(str1.equals(str2)); // true

System.out.println(s1 == s2); // true
System.out.println(str1 == str2); // false

== 으로도 비교가 가능한데 문자열이 같다고 보장하지 않는다. -> equals를 쓰자..

0개의 댓글