String Compare in Java | String Comparison

In this tutorial, we will learn how to compare two strings in Java with the help of examples. We will explore various methods to compare between the two strings.

In Java, or any other programming languages, string comparison is the process of evaluating whether two sequences of characters, commonly known as “strings,” are the same or different, i.e. equal or not. It is one of the fundamental string operation in Java that we use for various purposes, including searching, sorting, and data validation.

String compare in Java can be case-sensitive, meaning that the distinctions are made based on the uppercase and lowercase letters in a string of characters. In a case-sensitive, uppercase and lowercase letters are considered different and are treated as distinct strings.

For example, in a case-sensitive comparison:

  • “Apple” is not the same as “apple” because of the first uppercase letter “A”.
  • “Cat” is different from “cat” because of the uppercase “C.”

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 we 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.

Java String class provides two general methods for comparing the two strings. They are as follows:

  • equals() method
  • equalsIgnoreCase() method

Let’s understand all of them one by one.


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 are in the same order.


2. public boolean equalsIgnoreCase(String str)

This method performs the comparison between two strings by ignoring case differences. 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 being in the same order.


Let’s take an example program in which we will compare two strings by using equals() method of string class.

Program code 1:

package stringPrograms; 
public class EqualsMethodTest { 
public static void main(String args[])
{ 
// Creating two string literals.
   String s1 = "Hello"; 
   String s2 = "Hello"; 
 
// Creating two string objects with values "Good bye" and "Hello".
   String s3 = new String("Good bye"); 
   String s4 = new String("Hello"); 

// Compares the content of s1 and s2 using the equals method.
   System.out.println(s1.equals(s2)); // true because content and case is same.

// Compares the content of s1 and s3 using the equals method. 
   System.out.println(s1.equals(s3)); // false because the content is different. 

// Compares the content of s1 and the argument 'args'.
   System.out.println(s1.equals(args)); // false because 'args' is not equal to "Hello". 

// Compares the content of s1 and a null value.
   System.out.println(s1.equals(null)); // false because null is not equal to "Hello".

// Compares the content of s2 and s4 using the equals method and if-else statement.
// Since s2 and s4 have the same content ("Hello"), it prints "Both strings are equal".
   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

In this example code, we have created two string literals. When we have compared them using the equals method, it returns “true” because the content is the same (“Hello”). Then, we have created two string objects using the new keyword. When comparing s1 and s3, it returns “false” because their content is different.

Now we have compared the content of s1 with other data types and null. When comparing with a non-string value like ‘args’ or null, it returns “false” because they are not equal to the content of s1. At last, we have performed the comparison between s2 and s4 using if-else statement. Since they both have the same content (“Hello”), it prints “Both strings are equal.”


Let’s take another example program in which we will compare two strings by using equalsIgnoreCase() method.

Program code 2:

package stringPrograms; 
public class EqualsIgnoreCaseTest { 
public static void main(String args[])
{ 
   String s1 = "GOOD BYE"; 
   String s2 = new String("Good bye"); 

// This statement will print false because content is the same, but the case is different.
   System.out.println(s1.equals(s2));

// This statement will print true because the content is the same 
// due to ignoring differences in letter casing (uppercase or lowercase).   
   System.out.println(s1.equalsIgnoreCase(s2));  
  } 
}
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 in which we will compare two strings using double equal operator concept.

Program 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 copy 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.


Let’s take another example program based on double equal operator.

Program 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.

String comparison 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 returns false.

4. (s3 == s4): Since both s3 and s4 are pointing to the same object. Therefore, it will return true.


Key points:

1. Whenever we 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 further future purposes.

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 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 strings is converted into a Unicode value for comparison. The general form of this method is as 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 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.

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 take a simple example program in which we will compare two strings using compareTo() method of string class.

Program 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. 

// This statement will print 0 because both are equal.
   System.out.println(s1.compareTo(s2)); 

// This statement will print -5 because 'm' is 5 times lower than 'm'.
   System.out.println(s1.compareTo(s3)); 

// This statement will print -3 because 'm' is 3 times lower than 'p'. 
   System.out.println(s1.compareTo(s4));  

// This statement will print 2 because 'r' is 2 times greater than 'p'.
   System.out.println(s3.compareTo(s4));  

// This statement will print 4 because there are 4 characters in pune, whereas empty string has no characters. 
   System.out.println(s4.compareTo(s5)); 
 } 
}
Output: 
       0 
      -5 
      -3 
       2 
       4

Difference between == and equals() while comparing strings


== operator compares references of the string objects. It does not compare contents of string objects whereas, equals() method compares the contents of objects.


In this tutorial, we have discussed all important points related to string compare in Java with the help of various example programs. Hope that you will have understood how to compare two strings and practiced all programs.

The first two methods for string comparison are very important for interview purpose. There are often asked questions on equals() and double equal operator methods from freshers and experienced levels. In the next, we will understand string concatenation in Java with important example programs.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love