1.

What is the difference between str1 == str2 and str1.equals(str2)?

Answer»

JAVA offers both the equals() method and the "==" operator for comparing objects. However, here are some differences between the two:

  • Essentially, equals() is a method, while == is an operator.
  • The == operator can be used for comparing references (addresses) and the .equals() method can be used to compare content. To put it simply, == checks if the objects point to the same memory location, whereas .equals() compares the values of the objects.

Example:

public class StringComparison{ public STATIC void main(STRING[] args) { String str1=new String("Scaler"); String str2=new String("Scaler"); System.out.println(str1 == str2); System.out.println(str1.equals(str2)); }}

Output:

falsetrue

In this example, two different String objects are being created, str1 and str2.

  • If str1 and str2 are compared using the == operator, then the result will be false, because both have different addresses in the memory. Both must have the same address in the memory for the result to be true.
  • If you use the equals method, the result is true since it's only comparing the values GIVEN to str1 and str2, even though they are different objects.


Discussion

No Comment Found