How to Compare Strings In Java

How to Compare Strings In Java | In Java, there is an option to compare two strings which usually returns the boolean value true or false. There are few methods and operators available to perform comparisons. In this section, we will discuss different ways available to compare two strings with examples.

Compare Strings Using compareTo()

The compareTo() methods take one parameter, i.e. it takes a string that needs to be compared as a parameter, and it returns 0 or difference between the first unmatched character. If the strings are equal it returns 0 else it returns the difference between the first unmatched character.

The below code returns 0 as the two strings are equal. 

public class Main {
   public static void main(String[] args) {
      String s1 = "Hello";
      String s2 = "Hello";
      System.out.println(s1.compareTo(s2));
   }
}

Output:-

0

Since both strings contain the same value, therefore, the compareTo() method returns 0. Now, lets us observe another program that returns other than 0 i.e. where the strings are not equal.

Java code to compare two strings

public class Main {
   public static void main(String[] args) {
      String s1 = "hello";
      String s2 = "Hello";
      System.out.println(s1.compareTo(s2));
   }
}

Output:-

32

The above code returns a value other than 0 because compareTo() compares the strings based on Unicode. It returns the number of differences between them. The first unmatched character is “h” and “H” in the given strings, the ASCII value of “h” is 104, and the ASCII value of “H” is 72. The difference between their ASCII value is 104 – 72 = 32.

Note:- To compare strings, we can also use compareToIgnoreCase() which ignores the alphabetical cases and then compares the string.

Compare String Using ==

The “==” operator checks where both the objects point to the same memory location or not. If the strings are the same and it points to a different location then == operator will return false.

public class Main {
   public static void main(String[] args) {
      String s1 = "Hello";
      String s2 = "Hello";
      System.out.println(s1 == s2);
   }
}

Output:-

true

In this case, the code returns true because both the string points to the same object. In Java, string values are stored based on the String pooling concept, where each unique string literal is placed in a pool and used everywhere.

For example:- when we first time initializes the string literal “Hello” for the s1 variable then it was not available in the string pool, therefore JVM will assign memory and place it in the string pool. In the next line, while initializing the s2 variable, JVM first check whether the string “Hello” is available in the string pool or not? If not available then assign memory and place it in the string pool, else use the existing memory location. Hence both variables s1 and s2 are referring to the same memory location.

The below code returns false because there are two different strings pointing to different objects.

public class Main {
   public static void main(String[] args) {
      String s1 = new String("Hello");
      String s2 = new String("Hello");
      System.out.println(s1 == s2);
   }
}

Output:-

false

String pooling concepts are applicable for only string literal, but not for the string object. Here “Hello” is the string literal but s1 and s2 are two different string objects. Both string objects have different memory locations, hence == comparison returns false.

Compare String Using equals()

The equals() method given in the Object class compare objects based on their reference, therefore comparison using == or equals() method of Object class produces the same result. If we want to compare objects based on their values then we have to override the equals() method in our class. Also see:- == vs equals() in Java

The equals() method is overridden in the String class to compare objects based on their values/content. Therefore when we call the equals() method on String class objects then it compares the string content but not their reference. Opposite to this, StringBuilder and StringBuffer class doesn’t override the equals() method, therefore, calling the equals() method on StringBuilder and StringBuffer object will compare their reference, not the content.

public class Main {
   public static void main(String[] args) {
      String s1 = new String("Hello");
      String s2 = new String("Hello");
      System.out.println(s1.equals(s2));
   }
}

Output:-

true

Java Compare Strings Alphabetically

We can use the compareTo() method to compare two strings alphabetically as it compares the cases also. If the string differs in case then it will return false. The compareTo() method returns a greater value if one string is greater than another string and returns less value if a string is lesser than another, returns 0 if they are equal.

Program description:- How to compare two strings in Java which is greater?

public class Main {
   public static void main(String[] args) {
      String s1 = new String("HellO");
      String s2 = new String("Hello");
      System.out.println(s1.compareTo(s2));
   }
}

Output:-

-32

In the code, We have changed the case of ‘o’ hence the code returns -32. To avoid this issue we can use compareToIgnoreCase() which compares irrespective of cases.

Java code to demonstrate compareToIgnoreCase()

public class Main {
   public static void main(String[] args) {
      String s1 = new String("HELLO");
      String s2 = new String("Hello");
      System.out.println(s1.compareToIgnoreCase(s2));
   }
}

Output:-

0

As compareToIgnoreCase() method is case insensitive it returns 0. The “HELLO” and “hello” are casewise different but contentwise both are the same.

How to Compare Two Strings in Java Using If

We can also compare two strings by using the if loop as well, just by passing the methods and operators available in java into if. In the code, we have used the “==” operator inside the if, but the difference is we can define our own messages by using if. 

public class Main {
   public static void main(String[] args) {
      String s1 = new String("HELLO");
      String s2 = new String("Hello");
      if (s1 == s2) {
         System.out.println("Equal");
      } else {
         System.out.println("Not Equal");
      }
   }
}

Output:-

Not Equal

String.equals() versus ==

This equals() method does the content comparison, that is it compares only the string content irrespective of its object whereas == operator checks where both the objects point to the same memory or not. If the strings are the same and it points to a different location then == operator will return false. Let us see the demo code for these.

public class Main {
   public static void main(String[] args) {
      String s1 = new String("Hello");
      String s2 = new String("Hello");

      System.out.println(s1.equals(s2));
      System.out.println(s1 == s2);
   }
}

Output:

true
false

As the equals method compares the content it has returned true, whereas the “==” compares the object referencing to it has returned false as both strings refer to different objects.

compareTo() Versus equals()

The compareTo() method compares two strings alphabetically as it compares the cases also and returns integer value whereas equals() only checks for the content and returns a boolean value.

public class Main {
   public static void main(String[] args) {
      String s1 = new String("Hello");
      String s2 = new String("HellO");

      System.out.println(s1.equals(s2));
      System.out.println(s1.compareTo(s2));
   }
}

Output:-

false
32

As the strings are not the same, they differ in case of equals() return false and compareTo() returns a greater value.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.