aspose file tools
The moose likes Java in General and the fly likes string/stringBuffer(equals method) Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "string/stringBuffer(equals method)" Watch "string/stringBuffer(equals method)" New topic
Author

string/stringBuffer(equals method)

srijan sharma
Ranch Hand

Joined: Jan 24, 2001
Posts: 32
hi all,
the folowing code

StringBuffer strlit=new StringBuffer("scjp");
StringBuffer strobj=new StringBuffer("scjp");
System.out.println(strlit.hashCode()==strobj.hashCode());
System.out.println(strlit==strobj);
System.out.println(strlit.equals(strobj));
gives output
false
false
false
but when we use string class
String strlit="scjp";
String strobj=new String("scjp");
System.out.println(strlit.hashCode()==strobj.hashCode())
;
System.out.println(strlit==strobj);
System.out.println(strlit.equals(strobj));
it gives
true
false
true
can somebody explain why equals is not giving true for StringBuffer as the contents are still same i.e. scjp

regards
srijan
Val Dra
Ranch Hand

Joined: Jan 26, 2001
Posts: 439
That's because stringbuffer did not override equals method it uses the default one provided by the Object.


Val SCJP <BR>going for SCJD
srijan sharma
Ranch Hand

Joined: Jan 24, 2001
Posts: 32
hi,
thanks for the answer. but i could not get the point (overriding concept here). does equals method behave differently for strings and sbuffers.
regads
srijan
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
No, StringBuffer.equals() does not behave in the same way as String.equals(). In the javadoc for StringBuffer, you can see that it just inherits the default implementation (Object.equals()), and The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).
In other words, two stringBuffer1.equals(stringBuffer2) only if stringBuffer1 == stringBuffer2. If you need to compare, sort, convert or otherwise process a StringBuffer, turn it into a String first.
- Peter

[This message has been edited by Peter den Haan (edited February 24, 2001).]
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: string/stringBuffer(equals method)
 
Similar Threads
Object
equals and == Confusion when using with String, StringBuffer
equals()method
String & String Buffer
string and string buffers