Java: String 문자열 비교에서 ==, != 아닌 equals() 메소드사용...

Java: String 문자열 비교에서 ==, != 아닌 equals() 메소드사용...

String

String은 int나 char 기본(Primitive type) 자료형과 근본적으로 다르다

String은 Wrapper class에 속한 객체며 참조형(Reference Type)이다

String 데이터 생성하기

Wrapper class의 데이터 생성에는 2가지 방법이 있다​

1. 리터럴 생성

public class Main { public static void main(String[] args) { String s = "문자열"; System.out.println(s); //"문자열" 출력 } }

2. new 연산자 이용

public class Main { public static void main(String[] args) { String s = new String("문자열"); System.out.println(s); //"문자열" 출력 } }

위 두 방법의 차이점은 저장 방식 이다

리터럴 방식으로 생성 ➔ String constant pool에 값을 저장

리터럴 방식으로 이미 "madplay"를 저장했다면 다른 리터럴 변수가 이 값을 참조해 데이터를 재활용한다

(*리터럴 방식으로 저장할 때 intern() 메소드가 실행되어 중복된 문자열이 있는지 확인한다)

new 연산자 사용 ➔ Heap에 값을 저장

"madplay"를 저장하면 자신만 참조할 수 있는 독자적인 공간을 생성한다

문자열 비교에서 == != 를 사용하지 않는 이유

==, != 는 참조형 변수 비교시 둘의 주소를 비교한다

String 데이터 타입은 같은 문자열 값을 가지더라도

문자열 값을 비교하지 않고 주소값을 비교하기 때문에

원하는 결과를 얻을 수 없다

public class Main { public static void main(String[] args) { String s = "문자열"; String s2 = "문자열"; System.out.println(s==s2); // true: 둘 모두 리터럴 방식으로 같은 주소를 참고한다 } }

public class Main { public static void main(String[] args) { String s = "문자열"; String s2 = new String("문자열"); System.out.println(s==s2); // false: 둘의 저장공간이 다르다 } }

public class Main { public static void main(String[] args) { String s = new String("문자열"); String s2 = new String("문자열"); System.out.println(s==s2); // false: 둘의 저장공간이 다르다 } }

equal( ) 사용

문자열의 주소가 아닌 값을 비교하는 메소드

문자열 비교에서 == !=를 사용하지 못하기 때문에 equal() 메소드를 사용해 비교한다

public class Main { public static void main(String[] args) { String s = new String("문자열"); String s2 = new String("문자열"); System.out.println(s.equals(s2)); // true 출력 } }

위 두 문자열은 각각 Heap에 저장되며 주소가 다르지만

equal() 메소드를 사용해 값을 비교할 수 있다

확장

문자열 뿐 아닌 Wrapper Class 모두 ==, !=를 사용할 때 값을 참조하기 때문에

값의 비교는 equal()을 사용한다

Integer 예시

public class Main { public static void main(String[] args) { Integer num = new Integer(10); Integer num2 = new Integer(10); System.out.println(num==num2); // false 출력 } }

new 연산자를 이용해 만들었으므로 각각 Heap에 저장,

== !=를 사용시 주소비교를 하기 때문에 둘의 값이 같다고 뜬다

public class Main { public static void main(String[] args) { Integer num = new Integer(10); Integer num2 = new Integer(10); System.out.println(num.equals(num2)); //true 출력 } }

equal을 사용해 Wrapper 클래스의 값을 비교한다

from http://devyoseph.tistory.com/144 by ccl(A) rewrite - 2021-11-08 22:28:00