String does override equals(), as seen in the extract from the source code below. Click here for source code.
However, it doesn't mean it uses this equals code all of the time. As you might know, Java starts out by interpreting the code from bytecode to machine code, and only after some time JIT compiles it into machine code. Now, at the stage of interpreting, the java.lang.String#equals method is used to compare strings. However, it's very slow. That's why, when JIT compiles the code, compiled code uses a different version of equals(), that is much faster (and not written in Java, I assume). Unfortunately, can't give you any details on this, so you'd have to dig into it yourself.
Coming back to your question, why override equals()?
- You can initialize a string as a literal, like the code you provided (String s = ".."). In this case, all strings are interned from the get-go. Quote from javadoc:
- All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java Language Specification
So you can compare them by references, using ==. And it'll work just fine! But imagine you initialize String like objects:
String s1 = new String("some string");
String s2 = new String("some string");
If you compare these two strings by ==, then the result would be false. That's because object strings are not interned by default. You'd have to manually do it by using .intern() on them, and then compare them by reference. Or, if you don't want to do it, that's where equals() comes in. Should you do s1.equals(s2) on object strings (not interned), the result would be true.
- However, interned strings are a bit of an evil thing. String pool has limited size, it cannot grow any further. And by the time you run your main() method, it already has a bunch of strings in it. So it's used by the system. Now, if you intern every single string you come across to then compare them by reference ("=="), can you image what would happen? :) String pool would simply run out of space, and that's baad.
If you want to know more about java.lang.String, I highly recommend you watch Alexey Shipilev. The link to the video presentation. He pretty much confirms everything I've written above.