Java String comparison compareTo()

Introduction

The method compareTo() from String class compares two string value for order.

The method compareTo() is specified by the Comparable<T> interface, which String implements.

It has this general form:

int compareTo(String str) 

Here, str is the String being compared with the invoking String.

The result of the comparison is returned and is interpreted as shown here:

ValueMeaning
Less than zeroThe invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
// A bubble sort for Strings.
public class Main {
  static String arr[] = {
    "HTML", "CSS", "HTML5", "Java", "Javascript" };
  public static void main(String args[]) {
    for(int j = 0; j < arr.length; j++) {
      for(int i = j + 1; i < arr.length; i++) {
        if(arr[i].compareTo(arr[j]) < 0) {
          String t = arr[j];/*  w w  w.  j  ava 2s.  c  o  m*/
          arr[j] = arr[i];
          arr[i] = t;
        }
      }
      System.out.println(arr[j]);
    }
  }
}

To ignore case differences when comparing two strings, use compareToIgnoreCase():

int compareToIgnoreCase(String str) 



PreviousNext

Related