I dont understand why compiler does not think "name1" and "sb" as containing the same value
Since equals() checks the equality of object references, not their contents, to use it to compare what these objects actually contain, you must redefine the method itself . As you know, the string class also overrides this method.
Here
String name1 = "Test"; StringBuilder sb = new StringBuilder("Test");
name1 is a reference to the string "Test", which of type String and sb contains a reference to an object of type StringBuilder, so they have completely different links. and thus equals returns false.
Now why System.out.println(name1.equals(s)); prints true because string literals can be interned , and when you do String s = new String("Test"); the reference to the interned string object is used, therefore they contain the same links.
As suggested by others, you should use sb.toString() instead of sb
Note the Difference between the type of the object and the type of the link to further refine your concepts.
source share