class strb { static public void main(String...string) { StringBuilder s1 = new StringBuilder("Test"); StringBuilder s2 = new StringBuilder("Test"); System.out.println(s1); System.out.println(s2); System.out.println(s1==s2); System.out.println(s1.equals(s2)); //Line 1 System.out.println(s1.toString()==s2.toString()); //Line 2 if(s1.toString()==s2.toString())System.out.println("True"); //Line 3 } }
And the output is
Test Test false false
Just have a quick question on .equals.
Regardless of the object content, does .equals
return true only if both the object references point to the same object ?
EDIT : Now I understand the part about the .equals
but why does Line 2 and Line 3 also not return true
?
EDIT : I believe ==
looks at the reference variable's address and so s1 and s2 cannot be equal.correct me if my assumption is not right
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
We can use the equals() method for comparing two strings in Java since the String class overrides the equals() method of the Object class, while StringBuilder doesn't override the equals() method of the Object class and hence equals() method cannot be used to compare two StringBuilder objects.
The Equals method uses ordinal comparison to determine whether the strings are equal. . NET Core 3.0 and later versions: The current instance and sb are equal if the strings assigned to both StringBuilder objects are the same. To determine equality, the Equals method uses ordinal comparison.
StringBuilder does not override the equals method.It inherit the equal method from Object class. Unless the references you are comparing to same objects, it will return false. String overrides the equals method,so objects will return true if they are meaningfully equivalent.
Yes, StringBuilder does not override Object's .equals() function
, which means the two object references are not the same and the result is false.
For StringBuilder
, you could use s1.toString().equals(s2.toString())
For your edit, you're calling the ==
operator on two different String objects. The ==
operator will return false because the objects are different. To compare Strings, you need to use String.equals()
or String.equalsIgnoreCase()
It's the same problem you were having earlier
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With