In Java, equals() checks whether two strings have the same characters. It returns true or false.
You pass the other value. It is required for a normal call. Do not use == to compare string text. == compares references.
Syntax
Call equals on the string. Start with this line.
java
boolean ok = a.equals(b);
Call
What it does
a.equals(b)
Returns true when a and b have the same characters.
"Java".equals(null) returns false. Prefer writing the literal first when one side might be null.
Library declarations
java
public boolean equals(Object anObject);
Parameters
Parameter
Description
anObject
Required. The other string or object to compare.
Return Value
Return Value
Description
true
The characters match.
false
The characters do not match, or the argument is null.
Java Examples
Example 1 — Compare Content
Check whether two strings contain the same text.
java
public class EqualsBasic {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
String c = "java";
System.out.println(a.equals(b));
System.out.println(a.equals(c));
}
}
Output
true
false
How It Works
Same text.a and b are both "Java" → true.
Case differs."Java" vs "java" → false.
Character by character.equals compares every letter in order.
Boolean result. Use it directly in println or an if.
Example 2 — equals vs ==
new String(...) creates a new object. Content can match even when == is false.
java
public class EqualsVsEqEq {
public static void main(String[] args) {
String a = "Hi";
String b = new String("Hi");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}
Output
false
true
How It Works
Two objects. Literal "Hi" and new String("Hi") are not the same reference.
== is false. It asks “same object?” — here, no.
equals is true. Both hold the characters H and i.
Rule of thumb. Compare string text with equals, not ==.
Example 3 — Null-Safe Literal Style
Put the constant on the left so a null variable does not crash. For case-insensitive checks, see equalsIgnoreCase.
java
public class EqualsNullSafe {
public static void main(String[] args) {
String input = null;
// safe: returns false
System.out.println("yes".equals(input));
// unsafe if uncommented:
// System.out.println(input.equals("yes")); // NPE
}
}
Output
false
How It Works
input is null. Calling a method on it would throw.
Literal first."yes".equals(input) runs on a real string.
Null argument.equals(null) returns false safely.
Avoid the reverse.input.equals("yes") throws NullPointerException.
Frequently Asked Questions
equals() checks whether two strings have the same characters and returns true or false.
== compares references. equals() compares character content.
Yes.
It returns false when called on a non-null string.
Calling equals on null throws NullPointerException.