In Java, is there a String that is not equal to itself? When will str.equals(str) be False?

Viewed 89

Could there be a string that str.equals(str) is False?

Or in another way:

if(!str.equals(str)){
    System.out.println("-1");
}

Is there any way that the println line of code gets covered by a test?

1 Answers

No, there couldn't. Here's the source code in java 17. As you can see, when the two objects are the same, the equals method always return true.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    return (anObject instanceof String aString)
            && (!COMPACT_STRINGS || this.coder == aString.coder)
            && StringLatin1.equals(value, aString.value);
}
Related