Java – Compare two Strings Lexicographically

To compare two strings lexicographically in Java, use String.compareTo() method. Call compareTo() method on this string, and pass the string we would like compare this string with as argument.

In the following example, we will compare str1 with str2.

If str1 is less than str2 lexicographically, then str1.compareTo(str2) returns a negative value. The negative value is the difference between str1 and str2.

Java Program

ADVERTISEMENT
public class Example {
	public static void main(String[] args) {
		String str1 = "apple";
		String str2 = "carrot";
		int result = str1.compareTo(str2);
		System.out.println("Result : " + result);
	}
}

Output

Result : -2

If str1 is equal to str2 lexicographically, then str1.compareTo(str2) returns a zero.

Java Program

public class Example {
	public static void main(String[] args) {
		String str1 = "apple";
		String str2 = "apple";
		int result = str1.compareTo(str2);
		System.out.println("Result : " + result);
	}
}

Output

Result : 0

If str1 is greater than str2 lexicographically, then str1.compareTo(str2) returns a positive value. The positive value is the difference between str1 and str2.

Java Program

public class Example {
	public static void main(String[] args) {
		String str1 = "mango";
		String str2 = "apple";
		int result = str1.compareTo(str2);
		System.out.println("Result : " + result);
	}
}

Output

Result : 12

Comparison of strings using String.compareTo() is case sensitive, meaning “Apple” is less than “apple” lexicographically. If we need to ignore case while comparison, we may use String.compareToIgnoreCase() method.

Java Program

public class Example {
	public static void main(String[] args) {
		String str1 = "Apple";
		String str2 = "apple";
		int result = str1.compareToIgnoreCase(str2);
		System.out.println("Result : " + result);
	}
}

Output

Result : 0

Conclusion

In this Java Tutorial, we learned how to compare two strings lexicographically in Java.