Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string and string buffers

 
nishesh chouhan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
#)
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�);
System.out.println(s1.equals(s2));



why the o.p is false ??
what does the equlas() method in
Strringbuffer class do
 
Madhu SK
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
System.out.println(sb1.equals(sb2));
i think u got it
Bye!
Farhan
 
Ravindra Mohan
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 :

equals
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.
Parameters:
anObject - the object to compare this String against.
Returns:
true if the String are equal; false otherwise.
Overrides:
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).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic