String.equals()
Compares the contents of two strings.
Available since: Java 1.0
Syntax
public boolean equals(Object anObject)Parameters
| Parameter | Type | Description |
|---|---|---|
| anObject | Object | The object to compare with. For true it must be a string with the same characters. |
Return value
booleantrue if both strings have the same characters.
Examples
equals() compares the contents while == compares object references:
void main() {
String a = "java";
String b = new String("java");
IO.println(a.equals(b));
IO.println(a == b);
}Output:
true
falseComparing with a string that may be null — put the literal on the left:
void main() {
String answer = null;
IO.println("yes".equals(answer));
}Output:
falseNotes
Always compare strings with equals(). The == operator sometimes "works" for literals, because identical literals are one object, but for strings read from input or built by the program it gives false.
Calling answer.equals("yes") when answer == null throws NullPointerException. Safe versions: "yes".equals(answer) or Objects.equals(answer, "yes").
See also
- String.equalsIgnoreCase() — Compares two strings ignoring letter case.
- String.compareTo() — Compares two strings in dictionary (lexicographic) order.
- == vs equals() — == compares primitive values and object references; equals() compares object contents.
- Objects.equals() — Compares two objects with equals(), safely for null.
Related recipes
In the tutorial
- Strings — The String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.