Java String Compare | Example & Memory Explanation - Scientech Easy

Java String Compare | Example & Memory Explanation

String Compare in Java


In Java, the two strings can be compared on the basis of content and reference. We cannot compare the two string by using relational operators like >, <, >=,<=, and !=. 
Basically, Java provides us three general ways by which you can compare between the strings.
1. By equals() method
2. By = = operator (double equal operators)
3. By compareTo() method.

String Compare by equals() method


The string equals() method is used to compare the original content of the string. It compares the two strings for equality. i.e. If any character is not matching, it returns false. If all the characters are the same, it will return true. The string class overrides the equals() method of the object class. 
String class provides two general methods for comparing strings.

1. public boolean equals(Object str) 
Here, str is a specified string object in the method argument being compared with the calling string object. If the strings contain the same characters in the same order, it will return true otherwise false. 
For example:
   String str="Hello Java";
   boolean result=str.equals("Hello Java");
The result will be true because both are having the same set of string characters and in the same order.

2. public boolean equalsIgnoreCase(String str)
This method performs the compersion between two strings by ignoring the case difference. i.e, it only checks the content characters. When it compares the two strings, it considers the uppercase (A-Z) to be the same as the lowercase (a-z). If any character is not matched, it returns false otherwise, it returns true.
For example:
    String str="HELLO JAVA";
    boolean result=str.equals("hello java");
The result will be true because both are having the same set of string characters due to ignoring case difference and in the same order.
Let's see simple example programs to demonstrate the equals() and equalsIgnoreCase().
Program source code 1:
    package stringPrograms; public class EqualsMethodTest { public static void main(String args[]){ String s1="Hello"; String s2="Hello"; String s3=new String("Good bye"); String s4=new String("Hello"); System.out.println(s1.equals(s2)); // true because content and case is same. System.out.println(s1.equals(s3)); // false because content is different. System.out.println(s1.equals(args)); // false. System.out.println(s1.equals(null)); // false. if (s2.equals(s4)) { System.out.println("Both strings are equal"); } else System.out.println("Both strings are unequal"); } }
    Output: true false false false Both strings are equal
Program source code 2:
    package stringPrograms; public class EqualsIgnoreCaseTest { public static void main(String args[]){ String s1="GOOD BYE"; String s2=new String("Good bye"); System.out.println(s1.equals(s2)); // false because content is same but case is different. System.out.println(s1.equalsIgnoreCase(s2)); // true. } }
    Output: false true
Although the above two methods are the easiest ways to compare the strings. But the string class gives you many other options.

String Compare by = = operator


The = = operator (double equal operator) compares two object references, not characters. i.e, it compares the memory address of the object references. If both references are pointing to the same object then it will return true. But if they are pointing to the different objects, it will automatically return false.
Let's take a simple example program to understand double equal operator concept.
Program source code 3:
    package stringPrograms; public class DoubleEqualOperatorTest { public static void main(String args[]){ String s1="Cricket"; String s2="Cricket"; String s3=new String("Cricket"); System.out.println(s1==s2); // true System.out.println(s1==s3); // false } }
    Output: true false
Let's see the memory details to understand the output of this program very clearly.
Java String compare
Explanation of the allotting memory for storing object: 
1. Let us take the first statement: String s1="Cricket";
When JVM execute the first statement, it will create an object in the string constant pool and stores "Cricket" in it. The reference variable s1 which contains the address of the object says 365a25 is allocated to this object in the memory.
2. When the second statement String s2="Cricket"; will be executed by JVM, it will search in the SCP area to know whether the object with the same content is already available there or not. Since the same object is already present in the pool, it will simply create another reference variable s2 and copies the address of the reference variable s1 into s2. That's why s2 will also point to the same object. 

3. During the execution of the third statement String s3=new String("Cricket"); JVM will create another object in the heap area and allocate another address of the reference variable s3 says 19821f. since we know that for every string literal, JVM also creates one copy of the object in the string constant pool. But the object "Cricket" is already available in the pool. Therefore, it will not create another copy of the object. 

Explanation of the output of the above program:
1. When the statement (s1==s2) will be executed, JVM will compare the reference number (address) of the reference variable s1 and s2. Since both have the same reference number. Therefore, the output will be true.  
2. When the statement (s1==s3) will be executed, JVM will compare the reference numbers (addresses) i.e, 365a25 and 19821f . Since both have a different reference number. Therefore, the output will be false.  
Program source code 4:
    package stringPrograms; public class DoubleEqualOperatorTest { public static void main(String args[]){ String s1=new String("Football"); String s2=new String("Football"); String s3="Football"; String s4="Football"; System.out.println(s1==s2); // false System.out.println(s1==s3); // false System.out.println(s1==s4); // false System.out.println(s3==s4); // true } }
    Output: false false false true
To understand the output of this program, let's see the memory details.
String compare in Java
Explanation of the allotting memory for storing object:
1. Whenever we create a string object using the new operator, compulsory, a new object will be created in the heap area and stores "Football" in it. The reference variables s1 and s2 which contain the address of the object says 19811a and 19821b, they are allocated for objects in the memory. 
We know that for every string literal, JVM will create another copy of the object in the SCP area.
2. Since the object with the same content is already available in the SCP area, JVM will not create another object with the same content in the pool. Simply, JVM will point out the reference variables s3 and s4 to the same object as shown in the figure.

Explanation of the output of the above program:
1. (s1==s2): From the memory diagram, since both reference variables s1 and s2 are pointing to the different objects. Therefore, it will return false.
2. (s1==s3): It will also return false because both are pointing to the different objects.
3. (s1==s4): It return false.
4. (s3==s4): Since both s3 and s4 are pointing to the same object. Therefore, it will return true.
Key points: 
1. Whenever you will create a string object using the new operator, compulsory a new object will be created in the heap area and another one copy will be created in the string constant pool for the further future purpose.
2. For every string literal, JVM will create a string object in the string constant pool.

String Compare by compareTo() method


The string compareTo() method compares the current string object with the specified string object in the method argument lexicographically and returns an integer value. Basically, It compares two strings on the basis of the Unicode value of each character in the string. Each character of both the strings is converted into a Unicode value for comparison. The general form of this method is given below.
  public int compareTo(String str)
Here, str is the specified string object being compared with the calling string object.

For example 1:
  s1.compareTo(s2); where s1 and s2 are two reference variables of the string literals.
➲ If s1 = = s2, this method returns zero. It means that the two strings are equal.
➲ If s1 > s2, +ve value. It means that the first string is lexicographically greater than the second string. 
➲ If s1 < s2, -ve value. It means that the first string is lexicographically less than the second string. 
For example 2:
    s1.compareTo("Hello Java"); where s1 is a string literal and its value is compared with the string specified in the method argument.

Let's take one example program to understand it.
Program source code 5:
    package stringPrograms; public class CompareToMethodTest { public static void main(String args[]){ String s1="mumbai"; String s2="mumbai"; String s3="ranchi"; String s4="pune"; String s5=""; // Empty string. System.out.println(s1.compareTo(s2)); // 0 because both are equal. System.out.println(s1.compareTo(s3)); // -5 because 'm' is 5 times lower than 'm'. System.out.println(s1.compareTo(s4)); // -3 because 'm' is 3 times lower than 'p'. System.out.println(s3.compareTo(s4)); // 2 because 'r' is 2 times greater than 'p'. System.out.println(s4.compareTo(s5)); // 4 because there is 4 characters in pune whereas empty string has no characters. } }
    Output: 0 -5 -3 2 4
Final words 
Hope that this tutorial will be useful for you to understand the concept of string comparison in Java with example programs and their memory explanation. We hope that you will have enjoyed this tutorial. The first two methods of string comparison are very important for interview purpose. There are often asked questions on the equals() and double equal operator method to the freshers and experienced level.