.compareTo()
The .compareTo()
method compares two strings lexicographically based on the Unicode value of each character in the string.
Syntax
stringA.compareTo(stringB);
Both stringA
and stringB
are required in order for the .compareTo()
method to work properly.
A value of 0
will be returned if the strings are equal. Otherwise, the following will happen:
- A number less than
0
is returned ifstringA
is lexicographically less thanstringB
. - A number greater than
0
is returned ifstringA
is lexicographically more thanstringB
.
A way to think about this lexicographical evaluation is noting the Unicode values for the following character sets:
Character Set | Range | Example |
---|---|---|
1 - 9 |
49 - 57 | "7".compareTo("3"); -> 55 - 51 = 4 |
A - Z |
65 - 90 | "A".compareTo("B"); -> 65 - 66 = -1 |
a - z |
97 - 122 | "z".compareTo("w"); -> 122 - 119 = 3 |
Note: This method is case-sensitive. The .compareToIgnoreCase()
can be used to ignore upper and lower case differences. Alternatively, the .equals()
method can used to compare strings without taking Unicode values into account.
Example 1
Compare "Codecademy"
to "Codecademy"
:
class CompareStringsLexicographically {public static void main(String[] args) {String word1 = "Codecademy";String word2 = "Codecademy";System.out.println(word1.compareTo(word2));// Output: 0}}
Example 2
Compare "Codecademy"
to "codecademy"
:
class CompareStringsLexicographically {public static void main(String[] args) {String word1 = "Codecademy";String word2 = "codecademy";System.out.println(word1.compareTo(word2));// Output: -32}}
Example 3
Compare "codecademy"
to "Codecademy"
:
class CompareLexicographically {public static void main(String[] args) {String word1 = "codecademy";String word2 = "Codecademy";System.out.println(word1.compareTo(word2));// Output: 32}}
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours