compareTo( ) in Java

By Mashoud Viewed: 32083 times Emailed: 292 times Printed: 340 times Bookmark and Share



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. A string is less than another if it comes before the other in dictionary order. A string 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 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:

 

 

Value                                    Meaning
Less than zero                     The invoking string is less than str.


Greater than zero                T he invoking string is greater than str.
Zero                                      The two strings are equal.

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

// 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]);
}
}
}

The output of this program is the list of words:

Now
aid
all
come
country
for
good
is
men
of
the
the
their
time
to
to

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( ), shown here:

int compareToIgnoreCase(String str)

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




Comments(8)


1. how i can used inheritence ?


By: samee at 2008-02-16 12:54:27
2. Hi you can find inheritance example in Java in the following tutorial.

http://www.java-samples.com/showtutorial.php?tutorialid=658

By: Mashoud at 2008-04-26 20:12:37
3. Superb

many thanks to you Mashoud. i'm trying to learn Java in CNAM France and this code saved me 3 hours i was trying to class String arg ..... you saved me me....

By: orchidouest at 2009-05-10 12:58:53
4. know someone how to compare various objects?
I would like to have only one comparator for object like String, Long, Date...
but these objects come as "Object"s
any help?

By: Peter at 2009-10-07 07:32:31
5. Example:

String sOne = "hello there";
String sTwo = "hallo there";

What would my output be in this situation?

out.print(sOne.compareTo(sTwo));

and in this situation...

out.print(sTwo.compareTo(sOne));

By: Adam at 2009-11-10 12:55:51
6. @Adam:
CompareTo returns the difference of the ASCII codes of the first non-matching character. So,

out.print(sOne.compareTo(sTwo)); would display
// (sTwo - sOne)
('a' - 'e') which is -4.
and
out.print(sTwo.compareTo(sOne)) would display
//(sOne - sTwo)
('e' - 'a') which is 4.

Hope this will help you.

By: Azher at 2010-01-29 12:23:39
7. hi,
Very nice tutorial. But please I have some problems with this function. here is my problem:
I have created a dictionary that uses text files as database. The text files are encoded in UTF-8 format. I read them with InputStreamReader(is, "UTF-8");
and save them in an array of string. Nothing problem till here.
But the problem will start when I want to compare individual elements with the text I want. The loop passes through the correct one but using String.compareTo() will not stop it.
I have used different methods to decode both texts but nothing worked.
Any help will be appreciated.

By: hemn at 2010-04-17 06:02:00
8. You talk about "dictionary order". How would you sort the strings
"item 11", "item 5"?

By: Magnus A at 2010-08-31 22:58:06

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-09-02]Steps in using verisign certificate with Glassfish appserver
[2010-08-02]emulator 0 terminated while waiting for it to register!
[2010-08-02]Cannot run program "C:\Program Files\Java\jre6\bin\javac.exe": CreateProcess error=2, The system cannot find the file specified
[2010-08-01]Step by Step guide to setup freetts for Java
[2010-07-31]Speech Packages available for Java API
[2010-07-31]Tutorial on setting up freetts with maven
[2010-07-31]package com.sun.speech.freetts does not exist.
[2010-07-31]Text to Speech conversion program in Java
[2010-07-31]How to create wav file using freetts
[2010-07-31]How to set the width of a Text element in JavaFX?
[2010-07-31]Major components of FxObjects in JavaFX
[2010-07-03]Using the AWS SDK for Java in Eclipse
[2010-07-03]Using the AWS SDK for Java
[2010-01-01]Converting properties using PropertyEditors and Other Spring features worth mentioning
[2010-01-01]How to create an array and method in JSP

More Latest News

Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
XML and Java - Parsing XML using Java Tutorial
How to use Iterator in Java
How to Send SMS using Java Program (full code sample included)
Using StringTokenizer in Java
Using substring( ) in Java
FileReader and FileWriter example program in Java
indexOf( ) and lastIndexOf( ) in Java
HashMap example in Java
wait(), notify() and notifyAll() in Java - A tutorial
Abstract classes in Java
compareTo( ) in Java
Method Overriding in Java
instanceof sample program in Java
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Most Emailed Articles (in last 30 days)
Components of program
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Why java is important to the Internet
How to use ArrayList in Java
Execute system commands in a Java Program
FileReader and FileWriter example program in Java
Recursion in java
indexOf( ) and lastIndexOf( ) in Java
What is Java?
Method Overloading (function overloading) in Java
compareTo( ) in Java
Sample Java Script that displays a movable clock
History of Object
How to use Iterator in Java