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 Source

public class Javaapp {

       public static void main(String[] args) {

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

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


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

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


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

Leave a Comment