1.

How to compare two strings in Java

Answer»

Using compare methods

Compare two strings in Java using the compareTo() and compareToIgnoreCase() methods. The compareTo() method is used to compare two strings lexicographically or in dictionary order. Each CHARACTER is translated into a Unicode VALUE for comparison. If both the strings are equal, it returns 0 otherwise it returns positive or negative values.

The compareTo() method returns a positive value if the first string is lexicographically greater than the second string and it returns a negative value if the first string is lexicographically lesser than the second string. The compareToIgnoreCase() method compares two strings lexicographically irrespective of their cases.

Let us SEE an example where compareTo() and compareToIgnoreCase() methods are used to compare two strings:

public class Example {   public static void MAIN(String args[])   {      String s1 = "Same string";      String s2 = "same string";      int a1= s1.compareTo(s2);      int a2=s1.compareToIgnoreCase(s2);      if(a1<0)        System.out.println("String s2 is greater");      else if(a1>0)        System.out.println("String s1 is greater");      else        System.out.println("String s1 is equal to String s2");     if(a2==0)        System.out.println("After Ignoring the case, s1 and s2 are equal");      else        System.out.println("Even after ignoring the case, s1 and s2 are not equal");   } }

The output is as follows:

$javac Example.java $java Example String s2 is greater After Ignoring the case, s1 and s2 are equal

Using equals() and equalsIgnoreCase()

The equals() method compares the string to a specific object. It returns a boolean value either true or false. It returns true when argument is not NULL and the string matches the characters of the object. The equalsIgnoreCase() does the same operation but does not take into account the case of the string and the sequence of characters of the object.

Let us see an example where equals() and equalsIgnoreCase() are used to compare two strings.

public class Example {   public static void main(String []args)   {      String s1 = "Same String";      String s2 = "same string";      System.out.println(s1.equals(s2));      System.out.println(s1.equalsIgnoreCase(s2));   } }

The output is as follows:

$javac Example.java $java Example false true

Using the == operator

We can use the == operator to compare two strings. This operator acts like the equals() method and returns a boolean value as the result.

Let us see the application of == operator for comparison of two strings:

public class Example {   public static void main(String []args)   {      String s1 = "Same String";      String s2 = "same string";      String s3 = "Same String";      System.out.println(s1==s2);      System.out.println(s1==s3);   } }

The output is as follows:

$javac Example.java $java Example false true


Discussion

No Comment Found