Java compareTo() Method: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-04 04:00:11   7586  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. Astring is less than another if it comes before the other in dictionary order. Astring is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose. It has this general form:

int compareTo(String strng);

Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted, as shown here:

Value Meaning
Less than zero The invoking string is less than strng.
Greater than zero  The invoking string is greater than strng.
Zero The two strings are equal.

The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc.

However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type.

Syntax

public int compareTo( NumberSubClass referenceName )

Parameters

public int compareTo( NumberSubClass referenceName )

Parameters

Here is the detail of parameters ?

  • referenceName ? This could be a Byte, Double, Integer, Float, Long, or Short.

Return Value

  • If the Integer is equal to the argument then 0 is returned.
  • If the Integer is less than the argument then -1 is returned.
  • If the Integer is greater than the argument then 1 is returned.

Example


public class CompareToMethod {

   public static void main(String args[]) {
      Integer x = 12;

      System.out.println(x.compareTo(10));
      System.out.println(x.compareTo(12));
      System.out.println(x.compareTo(15));
   }
}

Output

1
0
-1
Press any key to continue . . .

Here is a sample program that sorts an array of strings. The program uses compareTo( ) to determine sort ordering for a bubble sort:

Program

// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country"
};
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];
				arr[j] = arr[i];
				arr[i] = t;
				}
			}
		System.out.println(arr[j]);
		}
	}
}

Output

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to
Press any key to continue . . .

As you can see from the output of this example, compareTo( ) takes into account uppercase and lowercase letters. The word “Now” came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( ), as shown here:

int compareToIgnoreCase(String str)

This method returns the same results as compareTo( ), except that case differences are ignored. You might want to try substituting it into the previous program. After doing so, “Now” will no longer be first.

Various type of compareTo() Method and their Description

Methods Description
int compareTo(Float f )  Compares the numerical value of the invoking object with that
of f. Returns 0 if the values are equal. Returns a negative
value if the invoking object has a lower value. Returns a
positive value if the invoking object has a greater value.
int compareTo(Double d ) Compares the numerical value of the invoking object
with that of d. Returns 0 if the values are equal.
Returns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.
int compareTo(Byte b  Compares the numerical value of the invoking object
with that of b. Returns 0 if the values are equal.
Returns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.
int compareTo(Short s Compares the numerical value of the invoking object
with that of s. Returns 0 if the values are equal.
Returns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.
int compareTo(Integer i  Compares the numerical value of the invoking object
with that of i. Returns 0 if the values are equal.
Returns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.
int compareTo(Long l )  Compares the numerical value of the invoking object
with that of l. Returns 0 if the values are equal.
Returns a negative value if the invoking object has a
lower value. Returns a positive value if the invoking
object has a greater value.
int compareTo(Character c) It returns zero if the invoking object and c have the same value. It returns a negative value
if the invoking object has a lower value. Otherwise, it returns a positive value.
int compareTo(Boolean b ) Returns zero if the invoking object and b contain the
same value. Returns a positive value if the invoking
object is true and b is false. Otherwise, returns a
negative value.
final int compareTo(E e ) Compares the ordinal value of two constants of the
same enumeration. Returns a negative value if the
invoking constant has an ordinal value less than e ’s,
zero if the two ordinal values are the same, and a
positive value if the invoking constant has an ordinal
value greater than e ’s.
int compareTo(T obj) This method compares the invoking object with obj. It returns 0 if the values are equal. A
negative value is returned if the invoking object has a lower value. Otherwise, a positive
value is returned.
int compareTo(Date date ) Compares the value of the invoking object with that of date. Returns
0 if the values are equal. Returns a negative value if the invoking
object is earlier than date. Returns a positive value if the invoking
object is later than date.