Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string equals question

 
jim oberon
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
string s = ("some sentance")
stringBuffer sb = ("some sentance")

sb.equals(sb)
or
s.equals(sb)

Which one would be correct the sb or the s.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, note that the syntax is...

(There are variations on these, but these are closest to what you posted.)

Now, which use of equals is correct? Neither. A StringBuffer is not a String, and a String is not a StringBuffer.

If you check the API for the equals method in String...
The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

But StringBuffer does not override the equals method. Therefore, it uses the implemention defined in Object...
...this method returns true if and only if x and y refer to the same object (x == y has the value true).

If you really need to compare these, you should get a String from your StringBuffer and compare that to the other String.

API References:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html
 
jim oberon
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i need to figure out if the string of its String object is identical to the string of its StringBuffer object.
 
Sabarish Sasidharan
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for that you can try
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just call the toString method on the StingBuffer. This will return a String representation of what's in the buffer...

String sbs = sb.toString();

Then you can use String's equals method because you have 2 String objects.
 
jim oberon
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then you need to ask the StringBuffer for its String form, and compare that String to your original:

String aString = ...
StringBuffer aBuffer = ...
String anotherString = aBuffer.toString();
if (aString.equals(anotherString)) ...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic