Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Strings, StringBuffer and equals()  RSS feed

Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ! Can equals method be applied to StringBuffers ? can't it compare values of a String and StringBuffer? I ran the following code and got the answers as follows :
StringBuffer s7;
String s1 = new String("Usha");
String s2 = new String("Usha");
String s3 = "Usha";
String s4 = "Usha";
StringBuffer s5 = new StringBuffer("Usha");
StringBuffer s6 = new StringBuffer("Usha");
s7 = s6;
System.out.println("With ==");
if (s1==s2) { System.out.println("s1==s2");}
if (s3==s4) { System.out.println("s3==s4");}
if (s5==s6) { System.out.println("s5==s6");}
if (s1==s3) { System.out.println("s1==s3");}
if (s7==s6) { System.out.println("s7==s6");}
/* if (s3==s5) { System.out.println("s1==s2");}*/
System.out.println("With equals");
if (s1.equals(s2)) { System.out.println("s1.equals(s2)");}
if (s3.equals(s4)) { System.out.println("s3.equals(s4)");}
if (s5.equals(s6)) { System.out.println("s5.equals(s6)");}
if (s1.equals(s3)) { System.out.println("s1.equals(s3)");}
if (s1.equals(s5)) { System.out.println("s1.equals(s5)");}
if (s3.equals(s5)) { System.out.println("s3.equals(s5)");}
if (s7.equals(s6)) { System.out.println("s7.equals(s6)");}

The output I got was :
With ==
with equals

Here with equals, when it is comparing two string objects s1 and s2 it is returning true, and similarly it does compare StringBuffers,and gives true for s7 and s6. I know s6 and s7 point to the same reference. But why is it not comparing s5 and s6, similar to comparing s1 and s2 ? ie why is it not returning true?
Please ,can someone generally explain the working of equals()
and if it is used to compare the values in 2 objects, why can't it compare a String and StringBuffer. (the commented line gives a compiler error).
If this has already been discussed anywhere else in this forum, please give me the links also.
Thank you in advance
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Search for StringBuffer using the "Search" facility in this forum.
2. StringBuffer does not override the equals() method. So any combination involving a string buffer and equals method will retrun false.
3. new String(string) or new StringBuffer(string) will always create a new object. Thus the comparision using the reference variables will always be false.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!