'==' 연산자와 equals() 메서드는 둘 다 객체 비교를 위해 사용되지만, 그 동작 방식과 사용 목적에 차이점이 있습니다.
요약
'==' 연산자는 두 객체의 참조(메모리 주소)를 비교
'equals()' 메서드는 두 객체의 내용(값)이 같은지를 비교
int num1 = 10;
int num2 = 20;
int num3 = 10;
boolean result1 = (num1 == num2); // false
boolean result2 = (num1 == num3); // true
System.out.println(result1); // false
System.out.println(result2); // true
String str1 = new String("hello");
String str2 = new String("hello");
String str3 = str1;
System.out.println(str1 == str2); // false (참조가 다름)
System.out.println(str1 == str3); // true (참조가 같음)
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2)); // true (내용이 같음)
객체의 내용 비교를 위해서는 equals() 메서드를 사용하는 것이 일반적으로 더 적합하며, 참조 비교를 위해서는 == 연산자를 사용합니다.