There are several ways to compare two strings in Java.
equals()method compares the contents of two strings and returns
trueif they are equal, i.e., if they have the same characters in the same order. It returns
falseotherwise. Here's an example:
String str1 = "Hello"; String str2 = "World"; String str3 = "Hello"; System.out.println(str1.equals(str2)); // false System.out.println(str1.equals(str3)); // true
==operator compares the references of two objects. If the references are equal, the operator returns
true. Otherwise, it returns
String str1 = "Hello"; String str2 = "Hello"; System.out.println(str1 == str2); // true
However, it is important to note that the
== operator does not compare the contents of the strings. It only compares the references. This means that the following code will also print
String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println(str1 == str2); // false
Even though the strings
str2 have the same content, they are not equal because they are different objects.
compareTo()method compares two strings lexicographically. It returns an integer value that indicates the relationship between the two strings. The return value is:
String str1 = "apple"; String str2 = "banana"; String str3 = "apple"; System.out.println(str1.compareTo(str2)); // negative value System.out.println(str1.compareTo(str3)); // 0 System.out.println(str2.compareTo(str1)); // positive value
It's important to note that the
compareTo() method is case-sensitive, meaning uppercase letters are considered to have a different value than lowercase letters.
compareToIgnoreCase()method is similar to the
compareTo()method, but it ignores case differences.
String str1 = "Hello"; String str2 = "hello"; System.out.println(str1.compareToIgnoreCase(str2)); // 0
This is because the values of
str2 are equal, even though they differ in case.
These are the basic methods to compare strings in Java. Additionally, Java provides other methods like
endsWith(), etc., that allow you to perform more specific string comparisons based on your requirements. In general, the
equals() method is the most commonly used method for comparing strings.