File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes string equals question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "string equals question" Watch "string equals question" New topic

string equals question

jim oberon

Joined: Oct 26, 2005
Posts: 3
string s = ("some sentance")
stringBuffer sb = ("some sentance")


Which one would be correct the sb or the s.
marc weber

Joined: Aug 31, 2004
Posts: 11343

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:

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
jim oberon

Joined: Oct 26, 2005
Posts: 3
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

Joined: Aug 29, 2002
Posts: 73
for that you can try

Sab<br /> <br />Perfection does not come from belief or faith. Talk does not count for anything. Parrots can do that. Perfection comes through selfless work.<br />Swami Vivekananda
marc weber

Joined: Aug 31, 2004
Posts: 11343

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

Joined: Oct 26, 2005
Posts: 3
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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)) ...

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: string equals question
It's not a secret anymore!