Friday 10 August 2012

Java String Compare using compareTo and compareToIgnoreCase


This Java String compare example describes how Java String is compared with another Java String object using compareTo and compareToIgnoreCase methods of  the String class.

int compareTo(String anotherString)

Compares two strings lexicographically. 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.

int compareToIgnoreCase(String anotherString)

Compares two strings lexicographically, ignoring case differences.

See the example given below



public class JavaStringCompareExample {

 public static void main(String[] args) {

  // declare String objects

  String str = "Java";
  String anotherStr = "Programming";

  /**
   * Compares two strings lexicographically using
   * compareTo(String anotherString) method.
   **/
  int compare = str.compareTo(anotherStr);

  if (compare > 0) {

   System.out.println(str + " is greater than " + anotherStr);

  } else if (compare < 0) {
   System.out.println(str + " is less than " + anotherStr);

  } else {
   System.out.println(str + " is equal to " + anotherStr);
  }

  String str2 = "JAVA";

  // Compares two strings lexicographically,
  // ignoring case differences.

  if (str.compareToIgnoreCase(str2) == 0)

   System.out.println("Java is equal to JAVA ");
 }
}


The output is:


Java is less than Programming
Java is equal to JAVA

1 comment: