aspose file tools
The moose likes Java in General and the fly likes StringBuffer and String with equal method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "StringBuffer and String with equal method" Watch "StringBuffer and String with equal method" New topic
Author

StringBuffer and String with equal method

Jay Vaghela
Greenhorn

Joined: Feb 15, 2006
Posts: 22
Hi
Can somebody explain me why the output of following code is "false"?

String str ="ram";
StringBuffer sb = new StringBuffer(str);

System.out.println(str.equals(sb));
System.out.println(sb.equals(str));

Thanks in Advance !
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3670

Thuogh the value they contain same,they are two different types of objects (one is String and the other is StringBuffer).

Actually equals method of String checks for the object to be a type of String as well,whereas StringBuffer inherits the equals from Object which simply returns true if and only if both objects refers to the same object. So both conditions are false in this case.
[ December 17, 2008: Message edited by: Vijitha Kumara ]

SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Jay Vaghela
Greenhorn

Joined: Feb 15, 2006
Posts: 22
Thanks Vijitha
Its clear now...!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32649
    
    4
You do of course know how to tell from the API how the equals method works in a particular class?
Try
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: StringBuffer and String with equal method
 
Similar Threads
Why it prints like this here?
String Equals
Reversing a string
String and String Buffer
StringBuffer