GeeCON Prague 2014*
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
Author

string equals question

jim oberon
Greenhorn

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

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:
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


"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
sscce.org
jim oberon
Greenhorn

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
Sheriff

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
Greenhorn

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

Joined: Jul 08, 2003
Posts: 24187
    
  34

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]
 
GeeCON Prague 2014
 
subject: string equals question