String Compare in Java | Equals, CompareTo Methods

String Compare in Java


In Java, two strings can be compared on the basis of content and reference. We cannot compare two strings by using relational operators like >, <, >=,<=, and !=. 

Basically, Java provides us three general ways by which you can compare between two strings.
1. By equals() method
2. By = = operator (double equal operators)
3. By compareTo() method.

String Compare by equals() method in Java


The string equals() method is used to compare the original content of string. It compares two strings for equality. 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 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 case difference. It only checks the content characters. When it compares 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 differences and in the same order.
Let’s take 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 strings. But the string class gives you many other options.

String Compare by = = Operator in Java


The = = operator (double equal operator) compares two object references, not characters. i.e, it compares the memory address of 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.

String compare by = = operator in Java

Explanation of allotting memory for storing objects: 

1. Let us take the first statement: String s1 = “Cricket”;
When JVM executes the first statement, it will create an object in the string constant pool and store “Cricket” in it. The reference variable s1 which contains the address of 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 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 output:
1. When the statement (s1==s2) will be executed, JVM will compare reference numbers (addresses) of the reference variables 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 reference numbers (addresses) i.e, 365a25 and 19821f . Since both have different reference numbers. Therefore, 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, look at the memory details.

Strings compare by double equal operators in Java

Explanation of allotting memory for storing objects:

1. Whenever we create a string object using 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 addresses of object say 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 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:
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.

Java String Compare by compareTo method


The string compareTo() method compares the current string object with 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 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 a specified string object being compared with calling string object.

For example:
 1. s1.compareTo(s2); where s1 and s2 are two reference variables of string literals.
➲ If s1 = = s2, this method returns zero. It means that two strings are equal.
➲ If s1 > s2, +ve value. It means that first string is lexicographically greater than second string. 
➲ If s1 < s2, -ve value. It means that first string is lexicographically less than second string. 

2: s1.compareTo(“Hello Java”); where s1 is a string literal and its value is compared with string specified in the method argument.

Let’s create a program where we will compare two strings using compareTo() method.
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 has covered all important points related to string comparison in Java with example programs. I hope that you will have understood this useful topic and enjoyed it.

The first two methods for string comparison is very important for interview purpose. There are often asked questions on equals() and double equal operator method from freshers and experienced levels.

Thanks for reading!!!
Next ⇒ Java String Concatenation⇐ PrevNext ⇒

Leave a Comment