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

string and string buffers

nishesh chouhan
Ranch Hand

Joined: Nov 06, 2000
Posts: 37
StringBuffer s2=new StringBuffer ("hello"); //1
String s3 =s2.toString(); //2
System.out.println(s3.equals(s2)); //3

1) the output at 3 is "false" but it shud be true
2) if at 3 "equals" is replaced by "==" then it gives error . why??
StringBuffer s1=new StringBuffer(�ab�);
StringBuffer s2=new StringBuffer(�ab�);

why the o.p is false ??
what does the equlas() method in
Strringbuffer class do
Madhu SK

Joined: May 07, 2001
Posts: 12
1. The output is false, because according to JLS:
"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 String object."
However, in your program s2 is not a String object. Hence the result is false.
2. == test gives an error, beacuse accroding to Khalid Mughal's book:
To apply ==, the operands must be type compatible:it must be possible to cast one into the other's type. Otherwise it is a complile time error.
hope this helps
Farhan Tariq
Ranch Hand

Joined: May 14, 2001
Posts: 54
Hi Nishesh!
You should check the documentation properly, because there is no method "equals()" in StringBuffer class. But u wont get error because Object class' method "equals()" called, but it takes both operands as objects that means check their references only if match "true" return, else "false".
try to compile and run this code:
StringBuffer sb1 = new StringBuffer("ab");
StringBuffer sb2 = sb1;
i think u got it
Ravindra Mohan
Ranch Hand

Joined: Mar 16, 2001
Posts: 216
Hi Everyone,
Farhan has rightly pointed out StringBuffer does not overrides the <code>equals()</code> of Object class.
Before I explain the mechanism in the example of Nishesh.
I would like to quote API pertaining to equals method of String class :

public boolean equals(Object anObject)
Compares this string to the specified object. 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.
anObject - the object to compare this String against.
true if the String are equal; false otherwise.
equals in class Object

Case (1)

On the contrary in case (2) ,

Hope you are clear now.
Ravindra Mohan

[This message has been edited by Ravindra Mohan (edited May 15, 2001).]
I agree. Here's the link:
subject: string and string buffers
It's not a secret anymore!