Java 25 (LTS) reference · String Methods

Java String equals() Method

Compare the contents of two strings. Never use == for strings: it compares object identity, not text.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.equals(other)

Parameters

ParameterDescription
other
Object
The object to compare with.

Return value

true if the text is the same.

Examples

equals() vs ==
public class Main {
    public static void main(String[] args) {
        String a = "java";
        String b = new String("java");
        System.out.println(a == b);        // different objects
        System.out.println(a.equals(b));   // same text
        System.out.println(a.equalsIgnoreCase("JAVA"));
    }
}

Output

false
true
true

Run this on your computer — see “Get Started” for setup.

Null-safe comparisons
public class Main {
    public static void main(String[] args) {
        String input = null;
        System.out.println("yes".equals(input));   // safe: no NullPointerException
        System.out.println(java.util.Objects.equals(input, null));
    }
}

Output

false
true

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?