In Java, you can compare strings using various methods. Here are some common ways to compare strings in Java:
1. Using `equals()` method:
The `equals()` method compares the content of two strings to determine if they are equal.
“`java
String str1 = “Hello”;
String str2 = “World”;
if (str1.equals(str2)) {
System.out.println(“Strings are equal.”);
} else {
System.out.println(“Strings are not equal.”);
}
“`
2. Using `equalsIgnoreCase()` method:
The `equalsIgnoreCase()` method compares strings while ignoring their case.
“`java
String str1 = “hello”;
String str2 = “Hello”;
if (str1.equalsIgnoreCase(str2)) {
System.out.println(“Strings are equal (case-insensitive).”);
} else {
System.out.println(“Strings are not equal.”);
}
“`
3. Using `compareTo()` method:
The `compareTo()` method compares strings lexicographically (based on their Unicode values) and returns an integer that indicates their relationship.
“`java
String str1 = “apple”;
String str2 = “banana”;
int result = str1.compareTo(str2);
if (result == 0) {
System.out.println(“Strings are equal.”);
} else if (result < 0) {
System.out.println(“str1 comes before str2.”);
} else {
System.out.println(“str1 comes after str2.”);
}
“`
4. Using `compareToIgnoreCase()` method:
Similar to `compareTo()`, `compareToIgnoreCase()` compares strings lexicographically while ignoring case.
“`java
String str1 = “Apple”;
String str2 = “banana”;
int result = str1.compareToIgnoreCase(str2);
if (result == 0) {
System.out.println(“Strings are equal.”);
} else if (result < 0) {
System.out.println(“str1 comes before str2.”);
} else {
System.out.println(“str1 comes after str2.”);
}
“`
Remember that when comparing strings, it’s important to consider case sensitivity and the specific requirements of your comparison. Choose the appropriate method based on your needs.