YouTip LogoYouTip

String Compare

## Java String Comparison: `compareTo` and `compareToIgnoreCase` In Java, comparing strings is a fundamental operation used for sorting, searching, and validating data. While the `equals()` method is used to check if two strings are identical, the `compareTo()` and `compareToIgnoreCase()` methods are used for lexicographical (alphabetical) comparison. These methods compare strings character by character based on their Unicode/ASCII values and return an integer indicating whether one string is lexicographically less than, equal to, or greater than another. --- ## Method Signatures and Syntax The `java.lang.String` class provides the following methods for lexicographical comparison: ### 1. `compareTo(String anotherString)` Compares two strings lexicographically based on the Unicode value of each character. This comparison is **case-sensitive**. ```java public int compareTo(String anotherString) ``` ### 2. `compareToIgnoreCase(String str)` Compares two strings lexicographically, **ignoring case differences**. ```java public int compareToIgnoreCase(String str) ``` ### Return Values Both methods return an `int` value: * **`0`**: The two strings are lexicographically equal. * **A negative integer (`< 0`)**: The invoking string is lexicographically less than the argument string (it comes before the argument string in the dictionary). * **A positive integer (`> 0`)**: The invoking string is lexicographically greater than the argument string (it comes after the argument string in the dictionary). > **Note:** The returned integer represents the difference between the Unicode/ASCII values of the first non-matching characters in the two strings. If one string is a prefix of the other, the returned value is the difference in their lengths. --- ## Code Example The following example demonstrates how to use `compareTo()`, `compareToIgnoreCase()`, and how to handle comparisons when dealing with generic `Object` types. ### `StringCompareEmp.java` ```java public class StringCompareEmp { public static void main(String[] args) { String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; // 1. Case-sensitive comparison // 'H' (ASCII 72) minus 'h' (ASCII 104) = -32 System.out.println(str.compareTo(anotherString)); // 2. Case-insensitive comparison // "Hello World" is equal to "hello world" when ignoring case System.out.println(str.compareToIgnoreCase(anotherString)); // 3. Comparing a String with an Object's string representation System.out.println(str.compareTo(objStr.toString())); } } ``` ### Output ```text -32 0 0 ``` --- ## Key Considerations & Best Practices ### 1. `==` vs `equals()` vs `compareTo()` * Use **`==`** to check if two string references point to the same memory location (identity). * Use **`equals()`** to check if two strings contain the exact same sequence of characters (equality). * Use **`compareTo()`** when you need to determine the ordering of strings (e.g., sorting a list of names alphabetically). ### 2. Handling `NullPointerException` Both `compareTo()` and `compareToIgnoreCase()` will throw a `NullPointerException` if the argument passed is `null`, or if the invoking string object itself is `null`. Always perform a null check before comparing: ```java if (str1 != null && str2 != null) { int result = str1.compareTo(str2); } ``` ### 3. Natural Ordering in Collections Because the `String` class implements the `Comparable` interface, you can use `compareTo()` implicitly when sorting collections of strings using `Collections.sort()` or `Arrays.sort()`.
← String Last OccuranceEnv Version β†’