Skip to content

String.equals versus ==

In Java, the == operator compares primitive values or object references, while the equals() method is used to compare the logical contents of two objects.

For example:


java
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 string literals. The JVM stores identical literals in a shared string pool, so == returns true because they reference the same object. The equals() method also returns true because it compares the string contents.

In the third example, s3 and s4 are created with the new operator, so they are distinct objects in memory. The == operator returns false because it compares references, not contents. The equals() method returns true because String overrides it to compare character sequences.

Note: Calling equals() on a null reference throws a NullPointerException. For null-safe comparisons, use Objects.equals(s1, s2) or place the known non-null literal first ("Hello".equals(s1)). Additionally, equals() behavior depends on the class implementation; custom classes must override it to compare logical contents correctly.

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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.