String

String CompareTo Java Example

Photo of Nikos MaravitsasNikos MaravitsasMarch 10th, 2014Last Updated: May 13th, 2021
0 197 2 minutes read

In this post, we feature a comprehensive String CompareTo Java Example.In a previous post, Java Compare Strings Example, we showed how to compare two Strings in java. In that example the test was simple: check if twoString objects are equal. But consider the case when you have a collection ofStrings 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.

CompareTo Java - compare strings java

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 twoStrings 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 theString class API offers methods that do just that. These methods arecompareTo andcompareToIngonreCase.

1. String CompareTo Java Example

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” than 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 thecompareTo will returns1.charaAt(i) - s2.charAt(i).
  • If there is no index position at which they have a different character,compareTo will returns1.lenght() - s2.length();

Let’s see how you can use it:

StringCompareToExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
packagecom.javacodegeeks.core.lang.string;
 
publicclassStringCompareToExample {
 
    publicstaticvoidmain(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:

-10-178

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

2. Using compareToIgnoreCase

You can usecompareToIgnoreCase 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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
packagecom.javacodegeeks.core.lang.string;
 
publicclassStringCompareToExample {
 
    publicstaticvoidmain(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-10

You can also check theComparable Java Example to learn more!

3. More articles

4. Download the source code

This was a Java String CompareTo example.

Download
You can download the code of this tutorial here :String CompareTo Java Example

Last updated on May 13th, 2021

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Nikos MaravitsasNikos MaravitsasMarch 10th, 2014Last Updated: May 13th, 2021
0 197 2 minutes read
Photo of Nikos Maravitsas

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. 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.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.