Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

String.equals()

Compares the contents of two strings.

Available since: Java 1.0

Syntax

public boolean equals(Object anObject)

Parameters

ParameterTypeDescription
anObjectObjectThe 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
false

Comparing with a string that may be null — put the literal on the left:

void main() {
    String answer = null;
    IO.println("yes".equals(answer));
}

Output:

false

Notes

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

Related recipes

In the tutorial

  • Strings — The String type in Java: creating strings, joining with +, length, characters by index, escaping and comparing with equals.

Thanks for reading!

Donate to the site — we work hard for you.