Java-String Comparison

String Comparison

We use the == operator for comparing the values of two variables or expressions of any data type, such as int, float, double, char and boolean. But we have to use the equals( ) method of the String class for comparing two strings. This method is used to find the contents are same, that is two strings are equal or not. It returns true, if the string contain the same character in the same order, and false otherwise.

In the following program, the contents are same in str1 and str2. but they are distinct objects. So it returns false in ==. Because, the == operator compares two object reference, to see whether they refer to the same instance. Reference is nothing but memory address. It is also possible to create two or more reference to the same object.

Program

Program Source

public class Javaapp {

       public static void main(String[] args) {

              String str1 = new String(“hajsof”);
              String str2 = new String(“hajsof”);

              if(str1==str2)
              {
                       System.out.println(“str1==str2 is true”);

               }else{

                         System.out.println(“str1==str2 is false”);
                         System.out.println(“Because == tests object references only”);
               }

               if(str1.equals(str2))
               {
                       System.out.println(“str1.equals(str2) is true”);
                       System.out.println(“equals() is used to tests the string values”);

               }else{

                       System.out.println(“str1.equals(str2) is false”);
              }
      }
}

Leave a Comment