Compare Two Strings in Java
Problem
Comparing two strings lexicographically means checking which one would come first in dictionary order, based on the character codes at the first position where they differ.
Given two strings, determine whether the first is less than, greater than, or equal to the second in dictionary order.
Java Program
public class CompareStrings {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
int minLength = Math.min(str1.length(), str2.length());
int result = 0;
for (int i = 0; i < minLength; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
result = str1.charAt(i) - str2.charAt(i);
break; // found the first difference, no need to compare further
}
}
if (result == 0) result = str1.length() - str2.length(); // fall back to length if one is a prefix of the other
if (result < 0) {
System.out.println(str1 + " is less than " + str2);
} else if (result > 0) {
System.out.println(str1 + " is greater than " + str2);
} else {
System.out.println(str1 + " is equal to " + str2);
}
}
}Output
Core Logic
Comparing both strings character by character, and stopping at the first difference, determines their order the same way a dictionary would.
- 1The loop runs up to
minLength, the shorter of the two strings' lengths, to avoid an out-of-bounds comparison. - 2At each position,
str1.charAt(i) != str2.charAt(i)checks whether the characters differ. - 3The first difference found sets
resultto the difference between the two character codes andbreaks immediately. - 4If every character matched up to
minLength, the shorter string is considered smaller —resultfalls back to comparing the two lengths.
"apple" and "banana", the very first characters 'a' and 'b' differ, so the comparison stops immediately — 'a' comes before 'b', so apple is reported as less than banana.Key Point: The length-based fallback only matters when one string is a prefix of the other, like "cat" versus "catalog" — every character matches until the shorter string runs out, and the shorter one wins.
Why: The comparison only needs to scan up to the length of the shorter string before finding a difference, and it doesn't allocate anything beyond the comparison itself.
Key Concepts
Approach 2: Using compareTo()
public class CompareStringsBuiltin {
public static void main(String[] args) {
String str1 = "apple";
String str2 = "banana";
// compareTo() returns negative, positive, or zero, based on lexicographic order
int result = str1.compareTo(str2);
if (result < 0) {
System.out.println(str1 + " is less than " + str2);
} else if (result > 0) {
System.out.println(str1 + " is greater than " + str2);
} else {
System.out.println(str1 + " is equal to " + str2);
}
}
}
Output
Core Logic
In real code, there's no reason to write the comparison loop yourself — compareTo() already implements this exact character-by-character logic.
- 1
str1.compareTo(str2)returns a negative number ifstr1comes first, a positive number ifstr2comes first, or0if they're equal. - 2The sign of the result — not its exact value — is what determines the order, so the same three-way
ifcheck works here too. - 3No explicit loop is needed in your own code.
"apple".compareTo("banana") returns a negative number, so the same if (result < 0) branch reports apple as less than banana.Key Point: This is the version to actually use — the manual loop exists only to show what compareTo() is conceptually doing under the hood.
Why: compareTo() still performs the same kind of character-by-character scan internally, but that scan happens inside the JDK instead of your own loop.