compareTo( ) in Java

By: Mashoud Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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		The 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.


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(13)


1. View Comment

how i can used inheritence ?

View Tutorial          By: samee at 2008-02-16 12:54:27
2. View Comment

Hi you can find inheritance example in Java in the following tutorial. <br>
<a href="http://www.java-samples.com/showtutorial.php?tutorialid=658">http://www.java-samples.com/showtutorial.php?tutorialid=658</a>


View Tutorial          By: Mashoud at 2008-04-26 20:12:37
3. View Comment

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....


View Tutorial          By: orchidouest at 2009-05-10 12:58:53
4. View Comment

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?


View Tutorial          By: Peter at 2009-10-07 07:32:31
5. View Comment

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));


View Tutorial          By: Adam at 2009-11-10 12:55:51
6. View Comment

@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.


View Tutorial          By: Azher at 2010-01-29 12:23:39
7. View Comment

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.


View Tutorial          By: hemn at 2010-04-17 06:02:00
8. View Comment

You talk about "dictionary order". How would you sort the strings
"item 11", "item 5"?


View Tutorial          By: Magnus A at 2010-08-31 22:58:06
9. View Comment

It is really a nice example when you need to sort the object having some strings and some other data, and some other complex structure of your own.
To sort any string array we have direct method i.e. Arrays.sort(arrStr);

Thanks a lot for this nice work. :-)


View Tutorial          By: Ranjan at 2010-10-04 23:14:33
10. View Comment

how about soting you word? like your output will become like this::::!
aid
all
come
country
for
good
is
men
Now
of
the
the
their
time
to


View Tutorial          By: fury_2623@yahoo.com at 2011-01-27 16:40:51
11. View Comment

I am trying to figure out what our Professor did when he was doing this code. I can see he is type casting, but I cant understand the line 2 where he is having a ".a" after typecasting "0".
Can anyone please help me understand this code better?

1. public int CompareTo ( Object o )
2. if( this.a < (( Test)o).a )
3. return -1;
4. else if (this.a == (( Test )o).a)
5. return 0;
6. else
7. return 1;


View Tutorial          By: Abhishek at 2011-04-09 23:31:28
12. View Comment

i was told to write a class which wl work as String functions do manually..at a point a method called equalsEgnoreCase(Mystring rightStr) which was supposed to return true if the invoking Mystring object and rightStr are identical not..what should i do in this case??please someone help me..

View Tutorial          By: ireen at 2011-04-13 04:59:31
13. View Comment

This is the coding that I wanted...
This is the only place that I found this.

Thank you...


View Tutorial          By: Damith at 2012-05-16 17:26:10

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Mashoud
ThreadGroup Sample in Java
Converting Numbers to and from Strings using Java
Using toLowerCase( ) and toUpperCase( ) in Java
How to use regionMatches( ) in Java
startsWith( ) and endsWith( ) in Java
equals( ) Versus == in Java
compareTo( ) in Java
String Conversion and toString() in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to use ArrayList in Java
Student marks calculation program in Java
Count number of vowels, consonants and digits in a String in Java
FileReader and FileWriter example program in Java
Execute system commands in a Java Program
Palindrome String in Java
Why java is important to the Internet
Vector example in Java
Calculate gross salary in Java
Read from a COM port using Java program
Tomcat and httpd configured in port 8080 and 80
The Unary Operators example in Java
right shift operator, >>, in Java
Integer: byte, short, int, and long data types in Java
XML and Java - Parsing XML using Java Tutorial
Most Emailed Articles (in Java)
Using Charts in JasperReports
Introducing Nested and Inner Classes
Tomcat and httpd configured in port 8080 and 80
List all the serial and parallel ports in your system using Java
What is Unicode?
FileReader and FileWriter example program in Java
FilenameFilter - sample program in Java
Basics of Inheritance in Java
Method Overloading (function overloading) in Java
while - Iteration in java
how to use boolean data type in Java
equals( ) Versus == in Java
J2EE Components
Increment and Decrement Operator
Read from a COM port using Java program