2

I tried the following code in netbeans and I received the output value as false I want to know how the equal() works actually.

My code was:

StringBuffer x=new StringBuffer("Hey");
StringBuffer y=new StringBuffer("Hey");
System.out.println(x.equals(y));    // my output was false
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Ramesh
  • 2,297
  • 2
  • 20
  • 42

4 Answers4

1

Just look at the source code*.

You will see that it just calls Object's equals

public boolean equals(Object obj) {
    return (this == obj);
}

Also consider using StringBuilder see Difference between StringBuilder and StringBuffer

* If using Eclipse ctrl-click on the Object and if the source coded is loaded in your system, it will take you there

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

StringBuffer does not override the Object.equals method, so it is not performing a string comparison. Instead it is performing a direct object comparison. Your conditional may as well be if(s1==s2). If you want to compare the strings you'll need to turn the buffers into strings first.

See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html

Edit: I'm assuming we're in a Java world. If you're in a single-threaded environment, or your buffers are isolated to a single thread, you should really be using a StringBuilder instead of a StringBuffer.

Does the StringBuffer equals method compare content?

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Amit
  • 1,540
  • 1
  • 15
  • 28
  • 2
    Instead of posting the link as an answer you should have marked the question as a duplicate. Link only answers are not good answers anyway. – Guy Jun 21 '17 at 04:36
  • Thanks for your suggestion and I will do it from now.. – Amit Jun 21 '17 at 05:23
0

You are comparing to objects, not strings. And those are not equal. Call toString() on both Stringbuffers and compare the resulting strings.

JosefScript
  • 581
  • 6
  • 15
0

just it will compare weather two objects are equale to "this" or not example It is reflexive: for any non-null reference value x, x.equals(x) should return true