Java

== 와 .equals의 차이점

Ms.Pudding 2022. 1. 7. 03:28

==와 .equals 모두 객체 값을 비교하여 답을 찾는 것이다.

하지만 약간의 차이가 있다.

 

zoo 프로젝트를 만들 때, result를 입력하면 멈추는 반복문을 만들었다

while(true){
String input = sc.nextLine();

	if(input.equals("result")){
		break;
	}else{
		list.add(new Animals(input));
	}
    
}

이때 if문 안의 조건문 input.equals("result")을 input == "result"로 하면 반복문에서 빠져나오지 못한다.

둘은 대부분 비슷한 기능을 하지만 String의 경우,

.equals의 경우는 변수 안의 값을 찾아주고 == 오퍼레이터는 reference를 체크한다.

위의 경우 단순한 변수값 비교이기 때문에 .equals를 쓴다.

 

더 자세한 설명을 살펴보자 !!

 

차이점

  1. .equals는 메소드, ==는 오퍼레이터
  2. String에서 ==은 레퍼렌스를 비교하고 , ,equals()는 단순한 변수 값을 비교해준다.

 

// Java program to understand
// the concept of == operator
public class Test {
	public static void main(String[] args)
	{
		String s1 = "HELLO";
		String s2 = "HELLO";
		String s3 = new String("HELLO");
		System.out.println(s1 == s2); // true
		System.out.println(s1 == s3); // false
		System.out.println(s1.equals(s2)); // true
		System.out.println(s1.equals(s3)); // true
	}
}

 

true , false , true , true

 

이유 : s1과 s2는 다른 객체이지만 constant pool(메모리 저장공간)은 같은 공간이다.

따라서 == (레퍼렌스 타입 , 즉 메모리 위치를 비교해줌)은 같은 공간을 가르키기 때문에 true로 나옴

.equals는 s1과 s2의 변수값을 비교해주기 때문에 true로 나온다.

 

String s3 = new String("Hello")의 경우, new라는 키워드를 썼기 때문에 레퍼렌스 객체를 만들었음. 즉 새로운 메모리 공간을 만들어 준것이다. 따라서 == 비교로는 false가 나온다.

하지만 s1.equals(s3)는 단순 변수값을 비교해준 것이기 때문에 true로 표시된다.