Java String equals()

The equals() method returns true if two strings are identical and false if the strings are different.

Example


Syntax of equals()

The syntax of the String equals() method is:

string.equals(String str)

equals() Arguments

The equals() method takes a single argument.

  • str - the string to be compared

equals() Return Value

  • returns true if the strings are equal
  • returns false if the strings are not equal
  • returns false if the str argument is null

Example: Java String equals()

Here,

  • str1 and str2 are equal. Hence, str1.equals(str2) returns true.
  • str1 and str3 are not equal. Hence, str1.equals(str3) and str3.equals(str1) returns false.

Example 2: Check if Two Strings are Equal

Output

str1 and str2 are not equal

Example 3: Case-Sensitive Comparison

The equals() method performs case-sensitive comparison. Meaning "Java" and "java" are considered different strings.

Notes:

  • If you need to compare two strings ignoring case differences, use the Java String compareToIgnoreCase() method.
  • The equals() method is available for all Java objects (not only Strings). It is because the equals() method is also defined in the Object class (which is the superclass of all Java classes).

Also Read: Java String compareTo()