Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

String.equals — comparing string contents

String.equals compares string contents with case sensitivity. The == operator compares object identity rather than contents.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public boolean equals(Object anObject)

String.equals has the signature public boolean equals(Object anObject). It returns true only when the argument is a non-null reference to a String with the identical character sequence. It is case-sensitive: "Java".equals("java") returns false.

For references, == checks whether they refer to the same object. In the example, new String("Java") creates a separate object, so a.equals(b) returns true, whereas a == b returns false.

An argument of another type, such as StringBuilder, yields false even with matching contents. a.equals(null) returns false if a is not null. Calling a method on a null reference throws NullPointerException; writing "Java".equals(missing) avoids this problem.

Documentation scope: Java SE 21. The repository runtime and production runtime have not been attested.

Examples

public class Main {
    public static void main(String[] args) {
        String a = "Java";
        String b = new String("Java");
        String missing = null;

        System.out.println(a.equals(b));
        System.out.println(a == b);
        System.out.println(a.equals("java"));
        System.out.println(a.equals(new StringBuilder("Java")));
        System.out.println(a.equals(missing));
        System.out.println("Java".equals(missing));
    }
}

Result

true
false
false
false
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources