Unraveling the Mystery of String Equality in Java

The == Operator: A Reference Check

The == operator checks if two string objects are referencing the same memory location. In other words, it verifies if both variables point to the same object. This means that even if the strings have the same content, if they are stored in different memory locations, the == operator will return false.

The equals() Method: A Content Check

On the other hand, the equals() method checks if the content of two string objects is identical. It compares the actual characters within the strings, regardless of their memory locations. This means that even if the strings are stored in different memory locations, if their content is the same, the equals() method will return true.

Example 1: Differentiating == and equals()

Let’s consider an example to illustrate this concept:


String name1 = new String("Programiz");
String name2 = new String("Programiz");

System.out.println(name1 == name2); // returns false
System.out.println(name1.equals(name2)); // returns true

In this example, name1 and name2 are two separate string objects with the same content. The == operator returns false because they are referencing different memory locations. However, the equals() method returns true because their content is identical.

Example 2: The Same Object, Different Variables

Now, let’s consider another example:


String name1 = new String("Programiz");
String name2 = name1;

System.out.println(name1 == name2); // returns true
System.out.println(name1.equals(name2)); // returns true

In this case, name1 and name2 are referencing the same string object. Therefore, both the == operator and the equals() method return true.

By understanding the difference between the == operator and the equals() method, you can write more accurate and efficient Java code when working with strings.

Leave a Reply