0

I have the following lines from the Java code

{        
         String str1=new String("Vivek");
         String str2=new String("Vivek");
         StringBuffer str3=new StringBuffer("Vivek");
         StringBuffer str4=new StringBuffer("Vivek");
         System.out.println(str1.equals(str2));
         System.out.println(str3.equals(str4));
}

Now i get the output as following

    True
    False

I cant get why it prints true for String oject and false for objects of StringBuffer? Has it to do something with mutability of objects?

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176

2 Answers2

4

StringBuffer does not override equals so calls the method of the superclass Object. If you want to compare content use the toString method

System.out.println(str3.toString().equals(str4.toString()));

Note Since Java 1.5 StringBuffer has been superceded by StringBuilder as a non-threaded alternative

Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

Because the equals in class String has been over-written to compare the content while the equals in class StringBuffer remained inherited from class Object which compares the address.

See there javadoc for both and you will understand more.

In String.equals:

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.

Overrides: equals(...) in Object
Parameters:
anObject The object to compare this String against
Returns:
true if the given object represents a String equivalent to this string, false otherwise
See Also:
compareTo(String)
equalsIgnoreCase(String)

You may use:

str3.toString().equals(str4);
taper
  • 528
  • 5
  • 22