Java Program to Compare Strings

Object Oriented ProgrammingJava8Java Programming

You can compare two Strings in Java using the compareTo() method, equals() method or == operator.

The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string.

The result is a negative integer if this String object lexicographically precedes the argument string.

The result is a positive integer if this String object lexicographically follows the argument string.

The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true.

Example

Live Demo

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

The equals() method of the String class 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

Live Demo

public class StringCompareEqual{
   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

You can also compare two strings using == operator. But, it compares references to the given variables, not values.

Example

Live Demo

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
raja
Published on 26-Apr-2018 12:40:22
Advertisements