String
class provides equals
method for comparing two String objects.
Comparing two String variables:
String str1 = "Java";
String str2 = "Java";
if(str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
Output:
str1 and str2 are equal
However, this may result in NullPointerException
if str1 is null
. So, it is always better to check if the reference variable is not null, which is calling the equals method.
String str1 = null;
String str2 = "Java";
if (str1 != null && str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
Output:
str1 and str2 are not equal
You don’t have to null check for the variable that is being passed into equals
method.
String str1 = "Java";
String str2 = null;
if (str1 != null && str1.equals(str2)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
Comparing String variable with String literal
String str1 = "Java";
if ("Java".equals(str1)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}
Since, String literal “Java” is also a String
object, you can call String
methods on it. This style of comparison avoids null check for the String
variable.
Check for String inequality
String str1 = "Java";
if (!"Oracle".equals(str1)) {
System.out.println("str1 and str2 are not equal");
} else {
System.out.println("str1 and str2 are equal");
}
Ignore case while comparing
String str1 = "Java";
if ("JAVA".equalsIgnoreCase(str1)) {
System.out.println("str1 and str2 are equal");
} else {
System.out.println("str1 and str2 are not equal");
}