Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder .equals Java

Tags:

java

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

like image 414
UnderDog Avatar asked Sep 02 '13 04:09

UnderDog


People also ask

What does .equals mean in Java?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

How do I compare two StringBuilder strings?

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.

How do you check for equality in StringBuilder?

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.

Can you compare String and StringBuilder in Java?

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.


1 Answers

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

like image 51
hotforfeature Avatar answered Oct 11 '22 07:10

hotforfeature