How do I compare strings in Java

In Java, you can compare two strings using the equals() method, which returns true if the two strings have the same content, and false otherwise. Here is an example:

java
String str1 = "hello";
String str2 = "world";if (str1.equals(str2)) {
System.out.println("The two strings are equal");
} else {
System.out.println("The two strings are not equal");
}

Alternatively, you can use the compareTo() method, which compares two strings lexicographically (i.e., based on their Unicode values), and returns a negative integer, zero, or a positive integer, depending on whether the first string is less than, equal to, or greater than the second string, respectively. Here is an example:

java
String str1 = "hello";
String str2 = "world";int result = str1.compareTo(str2);if (result == 0) {
System.out.println("The two strings are equal");
} else if (result < 0) {
System.out.println("str1 is less than str2");
} else {
System.out.println("str1 is greater than str2");
}

Note that when using the compareTo() method, it is important to handle the case where the two strings have different lengths, as otherwise the method may throw an exception.