3

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?

CalmaKarma
  • 61
  • 4
  • 1
    Should be impossible since the first check is whether the object is the same before going through the string comparison https://stackoverflow.com/questions/15585573/how-does-default-equals-implementation-in-java-works-for-string – Martheen May 27 '22 at 03:48
  • 1
    I suppose you could try [monkey-patching](https://stackoverflow.com/q/42139413/1270789) and change the [`hashCode()` API](https://stackoverflow.com/a/11656642/1270789) to return random values. This would most likely have the additional side-effect of breaking everything, though... – Ken Y-N May 27 '22 at 03:50
  • @ken-y-n no first checks for equality https://hg.openjdk.java.net/jdk7u/jdk7u6/jdk/file/8c2c5d63a17e/src/share/classes/java/lang/String.java#l974 – tgkprog May 27 '22 at 03:57
  • You cannot replace ("monkey-patch") `String` from user code. And changing `hashCode` wouldn't work anyway because `String.equals` doesn't call `String.hashCode`. To change the behavior of `String.equals`, you would need to modify the Java codebase and build a custom JVM. But frankly there is no good reason to do what the OP is asking / suggesting anyway. – Stephen C May 27 '22 at 04:51
  • @StephenC I'm glad, I suppose, that my random idea would never work! "But frankly there is no good reason to do what the OP is asking / suggesting anyway." I felt this was more a theoretical question, like how `NaN != NaN` in the floating-point world. – Ken Y-N May 27 '22 at 06:24
  • The answer to the theoretical question is a simple No. If you tweak the behavior of `String` then it is not Java (tm) anymore. – Stephen C May 27 '22 at 06:41

1 Answers1

10

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);
}
Frank Yang
  • 373
  • 3
  • 8