Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Java String CompareTo Example

In a previous post, Java String Compare Example, we showed how to compare two Strings in java. In that example the test was simple : check if two String objects are equal. But consider the case when you have a collection of Strings and you want to sort it. Of course, equality check is not enough. You have to impose ordering somehow. In strings (words in general), you can use lexicographical ordering.

Lexicographical ordering, or dictionary ordering or alphabetic ordering, is the operation of sorting strings alphabetically as they would appear on a dictionary. The process of doing so is very simple.

Imagining two Strings as an array of characters, then two strings are different if one of the following holds:

  1. They have a different character in the same position
  2. They differ in length
  3. Both of the above

The sorting is done like so :

  1. Sequentially scanning the strings, find the first (common) position (or index) in which they have a different character.
  2. Compare the two characters using '<'  or '>'.
  3. The string with the smaller value lexicographically precedes the other.
  4. If there is no index position at which they have a different characher, then the shorter string lexicographically precedes the longer string.

It is that simple. And it is equally simple to implement that algorithm in Java. But you don’t have to bother as the String class API offers methods that do just that. These methods are compareTo and compareToIngonreCase.

Using compareTo

compareTo will lexicographically compare two strings ad return a negative number if the first string is “smaller” than the second, zero if the strings are equal or a positive number if the first string is “bigger” that the second. Now that returning number is calculated like so:

  • If a different character is found in the same position, let it be i, of the two strings the compareTo will return s1.charaAt(i) - s2.charAt(i).
  • If there is no index position at which they have a different character, compareTo will return s1.lenght() - s2.length();

Let’s see how you can use it:

StringCompareToExample.java:

package com.javacodegeeks.core.lang.string;

public class StringCompareToExample {

	public static void main(String[] args) {

		String a = "abcd";
		String b = "abce";
		String c = "abcd";

		System.out.println(a.compareTo(b));
		System.out.println(c.compareTo(a));

		b = "abcde";

		System.out.println(a.compareTo(b));

		a = "a random string";
		b =  "another string ";

		System.out.println(b.compareTo(a));

	}
}

The above prints out:

-1
0
-1
78

It is important to note that compareTo compares the strings based on the Unicode value of each character in the strings.

Using compareToIgnoreCase

You can use compareToIgnoreCase to lexicographically sort strings without taking case into consideration, e.g for a case-insensitive ordering. Internally it uses : Character.toLowerCase(Character.toUpperCase(character)) to convert all the characters of both strings to lower case.

Let’s see how you can use it:

StringCompareToExample.java:

package com.javacodegeeks.core.lang.string;

public class StringCompareToExample {

	public static void main(String[] args) {

		String st  = "abcd";
		String st2 = "abce";
		String st3 = "aBcE";
		
		System.out.println(st.compareToIgnoreCase(st2));
		System.out.println(st.compareToIgnoreCase(st3));
		System.out.println(st2.compareToIgnoreCase(st3));

	}
}

The above prints out:

-1
-1
0

Download the code

This was a Java String CompareTo example. You can download the code of this tutorial here : StringCompareToExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close