There are several ways to compare two strings in Java.
equals()
method:equals()
method compares the contents of two strings and returns true
if they are equal, i.e., if they have the same characters in the same order. It returns false
otherwise. 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:==
operator compares the references of two objects. If the references are equal, the operator returns true
. Otherwise, it returns false
.
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 true
:
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1 == str2); // false
Even though the strings str1
and str2
have the same content, they are not equal because they are different objects.
compareTo()
method: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:compareToIgnoreCase()
method is similar to the compareTo()
method, but it ignores case differences.0
:
String str1 = "Hello";
String str2 = "hello";
System.out.println(str1.compareToIgnoreCase(str2)); // 0
This is because the values of str1
and 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 equalsIgnoreCase()
, startsWith()
, 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.