In Java, comparing strings can be done using a variety of methods tailored to different needs. Below are the most commonly used methods for comparison:
This compares the objects' reference (memory address), not the content.
```java String str1 = "hello"; String str2 = "hello"; System.out.println(str1 == str2); // true, because both refer to the same object in the string pool String str3 = new String("hello"); System.out.println(str1 == str3); // false, because str3 refers to a different object ```
This compares the content of the strings.
```java String str1 = "hello"; String str2 = new String("hello"); System.out.println(str1.equals(str2)); // true, because their content is the same ```
This compares the content of the strings, ignoring case differences.
```java String str1 = "hello"; String str2 = "HELLO"; System.out.println(str1.equalsIgnoreCase(str2)); // true, because their content is the same, ignoring case ```
This method compares two strings lexicographically. It returns:
```java String str1 = "apple"; String str2 = "banana"; System.out.println(str1.compareTo(str2)); // negative number, because "apple" is less than "banana" ```
This method compares two strings lexicographically, ignoring case differences.
```java String str1 = "apple"; String str2 = "Banana"; System.out.println(str1.compareToIgnoreCase(str2)); // negative number, because "apple" is less than "Banana" ignoring case ```
In Java, string comparison methods vary depending on whether you must compare memory references, content, or lexicographical order and whether case sensitivity matters. Choose the method that best suits your specific needs.