I have written a sample program on equals and == for string buffer and string builder. As per my knowledge (which is right or wrong) equals will compare the two objects bit by bit and == compares two memory locations.
But its not working in case of string buffer and string builder. I am getting strange error when using == with string buffer and string builder and it is "incompatible operand types String and StringBuffer"
The == operator (when used on reference types) checks if the two operands refer to the exact same object.
When you try to compare to unrelated kinds of objects, for example a StringBuffer and a StringBuilder (they are not related through inheritance), the result will always be false - a StringBuffer object can never be the same object as a StringBuilder object. Since this is a useless comparison, the Java compiler doesn't allow you to compare them - it gives you an error message that tells you you can't compare two unrelated kinds of objects with ==.
Note that even when you have fixed the compilation problems you are not going to get the results you expect.
StringBuffer and StringBuilder do not override the equals method, so they will inherit it from the Object class and the Object class just compares the two objects using ==.
Swapna latha wrote:But its not working in case of string buffer and string builder. I am getting strange error when using == with string buffer and string builder and it is "incompatible operand types String and StringBuffer"
It is an order-of-operations thing. When being resolved, this will probably become System.out.println("In buffer hellow world"==s3); and you have a String being compared to StringBuffer. Put parenthesis around the s3==s3.
posted 5 years ago
Thanks to all. I got the concept. This forum is really awesome.