Java ProgramsStringsCompare Two Strings

Compare Two Strings in Java

beginner·  Strings  ·  String

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.

Input
"apple", "banana"
Output
apple is less than banana

Java Program

Java
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

apple is less than banana

Core Logic

Comparing both strings character by character, and stopping at the first difference, determines their order the same way a dictionary would.

How It Works
  1. 1The loop runs up to minLength, the shorter of the two strings' lengths, to avoid an out-of-bounds comparison.
  2. 2At each position, str1.charAt(i) != str2.charAt(i) checks whether the characters differ.
  3. 3The first difference found sets result to the difference between the two character codes and breaks immediately.
  4. 4If every character matched up to minLength, the shorter string is considered smaller — result falls back to comparing the two lengths.
For "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.

Complexity
Time Complexity: O(min(n, m))Space Complexity: O(1)

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

char comparisonfor loopearly exit with break

Approach 2: Using compareTo()

Java
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

apple is less than banana

Core Logic

In real code, there's no reason to write the comparison loop yourself — compareTo() already implements this exact character-by-character logic.

How It Works
  1. 1str1.compareTo(str2) returns a negative number if str1 comes first, a positive number if str2 comes first, or 0 if they're equal.
  2. 2The sign of the result — not its exact value — is what determines the order, so the same three-way if check works here too.
  3. 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.

Complexity
Time Complexity: O(min(n, m))Space Complexity: O(1)

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.

Key Concepts

String.compareTo()

Related Programs