JavaStringsIntermediate

String.compareTo()

Compares two strings lexicographically (based on the Unicode value of each character).

Review the syntaxStudy the examplesOpen the coding app
String.compareTo(String anotherString)

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Compares two strings lexicographically (based on the Unicode value of each character).

The `compareTo()` method in Java is used to compare two strings lexicographically. This means it compares the strings based on the Unicode value of each character. The method returns an integer: a negative integer if the current string is lexicographically less than the argument string, a positive integer if the current string is lexicographically greater than the argument string, and zero if the strings are equal. This method is essential for sorting strings or determining their relative order. It performs a character-by-character comparison. If strings are of different lengths and one is a prefix of the other (e.g., "apple" vs "applepie"), the shorter string is considered lexicographically smaller. The time complexity is O(n) where `n` is the length of the shorter string, as it iterates through characters until a difference is found or one string ends. For case-insensitive comparison, `compareToIgnoreCase()` is available. It's crucial for implementing custom sorting logic or using sorted data structures like `TreeMap` or `TreeSet` with strings.

Quick reference

Syntax

String.compareTo(String anotherString)

Inputs

Parameters

anotherStringString · The String to be compared.

See it in practice

Examples

1

Basic lexicographical comparison

String s1 = "apple";
String s2 = "banana";
String s3 = "apple";
String s4 = "apricot";

System.out.println("s1.compareTo(s2): " + s1.compareTo(s2));
System.out.println("s1.compareTo(s3): " + s1.compareTo(s3));
System.out.println("s1.compareTo(s4): " + s1.compareTo(s4));
Output:
s1.compareTo(s2): -1 s1.compareTo(s3): 0 s1.compareTo(s4): 1

Shows that 'apple' is less than 'banana' (-1), equal to 'apple' (0), and greater than 'apricot' (1, because 'p' comes after 'r').

2

Case-sensitive nature and different lengths

String s1 = "Java";
String s2 = "java";
String s3 = "Jav";

System.out.println("s1.compareTo(s2): " + s1.compareTo(s2));
System.out.println("s1.compareTo(s3): " + s1.compareTo(s3));
System.out.println("s1.compareToIgnoreCase(s2): " + s1.compareToIgnoreCase(s2));
Output:
s1.compareTo(s2): -32 s1.compareTo(s3): 1 s1.compareToIgnoreCase(s2): 0

Illustrates that 'Java' is less than 'java' due to ASCII values ('J' < 'j'). 'Java' is greater than 'Jav' because it's longer. `compareToIgnoreCase()` provides case-insensitive comparison.

3

Sorting a list of strings using compareTo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

List<String> names = new ArrayList<>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
Collections.sort(names); // Uses String.compareTo() internally
System.out.println(names);
Output:
[Alice, Bob, Charlie]

Demonstrates how `compareTo()` is implicitly used by `Collections.sort()` to sort a list of strings in natural (lexicographical) order.

Debug faster

Common Errors

1

Misinterpreting return value

Cause: Assuming `compareTo()` returns only -1, 0, or 1. While these are common, it can return any negative or positive integer representing the difference in Unicode values of the first differing characters.

Fix: Focus on the sign of the return value (negative, zero, positive) rather than its exact magnitude, unless specific ordering logic requires it.

String s1 = "a";
String s2 = "z";
int result = s1.compareTo(s2); // result is -25 (Unicode 'a' - 'z')

// Incorrect logic if expecting only -1:
// if (result == -1) { ... }

// Correct logic:
if (result < 0) {
    System.out.println("s1 is lexicographically smaller");
} else if (result == 0) {
    System.out.println("s1 and s2 are equal");
} else {
    System.out.println("s1 is lexicographically larger");
}

Runtime support

Compatibility

JVMN/AJava 1.0+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

Compares two strings lexicographically (based on the Unicode value of each character).

anotherString: The String to be compared.

Misinterpreting return value: Focus on the sign of the return value (negative, zero, positive) rather than its exact magnitude, unless specific ordering logic requires it.