Sunday, 22 May 2016

Comparing String with StringBuffer or StringBuilder

class StringTest1
  public static void main(String args[])
        // equality test b/w String and StringBuffer
        StringBuffer sb=new StringBuffer("ABC");
        String s=new String("ABC");

        System.out.println(s.equals(sb)); //#1
System.out.println(sb.equals(s)); //#2
System.out.println(s.equals(sb.toString())); //#3
System.out.println(sb.toString().equals(s)); //#4

        StringBuffer sb1 = new StringBuffer("ABC");

  System.out.println(sb == sb1); //#5
  System.out.println(sb.equals(sb1)); //#6
System.out.println(sb.toString().equals(sb1.toString())); //#7


Reason: String classs override equals() method of object class whereas StringBuffer and StringBuilder do not override equals() method. so StringBuffer and StringBuilder equals methods will

Below is the code for the equals method of the String class.

public boolean equals(Object anObject) {
if (this == anObject) 
    return true;
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
return true;
return false;

As you can see, the above method unconditionally returning false if the type of the given argument is not of type String. String and StringBuffer objects are always different as far as equals is concerned.
But, the condition can give us true if we will compare String with the content of the StringBuffer and not the StringBuffer itself. To get the content of the StringBuffer just invoke toString() on it.

equals method in Object class:
public boolean equals(Object obj) { return (this == obj); }

#1 : int this line, it will return false because of String class equals method. here, sb instanceof String will fail
#2 : in this line, StringBuffer class equals method checking the reference equality and that is not true
#3 : in this line, we are getting String object by calling toString() method and that will call String class equals method.  
#4 : same as #3
#5 : checking the reference equality by using ==
#6 : it will call StringBuffer equals method which is checking the reference equality
#7 : same as #3


  1. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks; from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai



Thanks for coming here. I hope this information helps you for preparing Java Interview.

Sachin Singh