If you look at the overridden equals() method within the String class you see that it checks if the object given as parameter is an instance of String. If it's not, it retuns false. And since you compare your String object with a StringBuffer object you get false.
The reason you got output as "Both are not equal" is you are comparing objects of different type. str is object of String class and sb is object of StringBuffer class When JVM finds comparison made between objects of two different classes, it invokes equals() method of Object class which thereby checks only if two variable are pointing to same object or not.
Hope this clears the reason why you got that output.
First of all apologies for late reply. What I said was that
WHEN JVM FINDS COMPARISON MADE BETWEEN TWO OBJECTS BELONGING TO TWO DIFFERENT TYPES IT INVOKES equals() method of Object class.
Reason why I said it is:
Every Object that is created is a derived from Object class. Now in this case we have equals() method overriden in String class. So what JVM does on encountering str.equals(sb) statement, it calls equals() method of String class. But since the object we passed as parameter is not a string object so what does it do, it calls equals() method of Object class.
There are two scenarios we can think of, when we see statement of this kind "objA.equals(objB)", Constraints: objA and objB belong to two different classes:
1) If objA's class has an equals method then in this case it will invoke its own equals() method and it will find objB is not of its own class type. Since it is not it will invoke equals() method of Object class. 2) If objA's class doesnot at all have equals() method then certainly it will call the equals() method of Object class.
I hope this clears why I gave that statement. May be I was wrong in framing it. But explanation I provided above is what I actually meant.
Seems like we are still on not same page on your comment which i quoted below.
1) If objA's class has an equals method then in this case it will invoke its own equals() method and it will find objB is not of its own class type. Since it is not it will invoke equals() method of Object class.
When we override our and provide implementation for equals() we can do this, but in String class defined in java.lang this is not the case. Please check code below from Java library as you can see from code below that there is no call to Object.equals() method
If its green its biology if its stinkks its chemistry if it has numbers it is Maths and if it doesn't work its TECHNOLOGY