Java Equality


Java Equality: Strings play a very important role in programming in every language. In Java, the string manipulation is simplified, by the Designers, by adding more methods in String class. One such method is equals().

Strings can be compared in Java in two ways using equals() method and logical ==. Let us see their difference of usage and which is preferable and safe.

Example on Java Equality
public class JavaEquality
{
 public static void main(String args[])
 {
   String str1 = "hello";
   String str2 = "hello";
   String str3 = new String("hello");

// when printed, all prints hello, let us compare their equality

   System.out.println("\nstr1 and str2 with equals(): " + str1.equals(str2));
   System.out.println("str1 and str2 with ==: " + (str1 == str2));

   System.out.println("\nstr1 and str3 with equals(): " + str1.equals(str3));
   System.out.println("str1 and str3 with ==(): " + (str1 == str3));
 }
}


Java Equality
Output screenshot on Java Equality

In the above code, str1, str2 and str3, all prints hello but they differ in how they are stored in memory by Java. str1 and str2 values hello are stored in string pool and str3 outside. That is, str1 and str2 refer the same hello location but not str3. For this reason str1 and str3 with equals() returns true but with ==, prints false. This is a big trap in Java coding. My advise is use always equals() to compare two strings but not == and do not bother much about locations.

For more details on Equality of two strings and the programming traps: Introduction – Immutable Nature – Comparison

Leave a Comment

Your email address will not be published.