How to Compare Two Strings in Java



String comparison is important in Java for tasks like matching, sorting, and authentication. This tutorial covers different ways to compare strings. The following are the various methods to compare strings based on their content or references

  • String compare by compareTo() method

  • String compare by equals() method

  • String compare by == operator

String compare by compareTo() method

The compareTo() method compares two strings based on their lexicographical order, using the Unicode values of each character. It returns 0 if the strings are equal, a value less than 0 if the first string is lexicographically smaller, and a value greater than 0 if the first string is lexicographically greater.

Example

The following example compares two strings by using str compareTo (string), str compareToIgnoreCase(String), and str compareTo(object string) of string class and returns the ASCII difference of the first odd characters of compared strings

public class StringCompareEmp{
   public static void main(String args[]){
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;
      System.out.println( str.compareTo(anotherString) );
      System.out.println( str.compareToIgnoreCase(anotherString) );
      System.out.println( str.compareTo(objStr.toString()));
   }
}

Output

-32
0
0

String compare by equals() method

The equals() method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Example

The following example compares the string by equals() method

public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1.equals(s2));
      System.out.println(s2.equals(s3));
   }
}

Output

true 
false 

String compare by == operator

The == operator compares two strings by their memory references, not their content. It returns true if they refer to the same object, and false if they don't.

Example

The following example compares the string by using the == operator

public class StringCompareequl{
   public static void main(String []args){
      String s1 = "tutorialspoint";
      String s2 = "tutorialspoint";
      String s3 = new String ("Tutorials Point");
      System.out.println(s1 == s2);
      System.out.println(s2 == s3);
   }
}

Output

true
false 
java_strings.htm
Advertisements