String.equals versus ==
In Java, the ==
operator is used to compare the primitive values of two variables, while the equals()
method is used to compare the contents of two objects.
For example:
int a = 1;
int b = 1;
System.out.println(a == b); // prints "true"
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // prints "true"
System.out.println(s1.equals(s2)); // prints "true"
String s3 = new String("Hello");
String s4 = new String("Hello");
System.out.println(s3 == s4); // prints "false"
System.out.println(s3.equals(s4)); // prints "true"
In the first example, a
and b
are both integers, so the ==
operator compares their values and returns true
because they are equal.
In the second example, s1
and s2
are both strings that have the same value, so the ==
operator returns true
because they refer to the same object in memory. The equals()
method also returns true
because it compares the contents of the strings, which are equal.
In the third example, s3
and s4
are both strings, but they are created using the new
operator, so they are distinct objects in memory. The ==
operator returns false
because it compares the memory addresses of the objects, which are different. The equals()
method, on the other hand, returns true
because it compares the contents of the strings, which are equal.
Therefore, it is generally recommended to use the equals()
method when comparing the contents of two objects, and to use the ==
operator only when comparing the primitive values of two variables.