File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes String Buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "String Buffer" Watch "String Buffer" New topic
Author

String Buffer

devi nachimuthu
Greenhorn

Joined: Jan 07, 2003
Posts: 10
What is the output of the following?
StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2 = new StringBuffer("Amit");
String ss1 = "Amit";
System.out.println(sb1 == sb2);
System.out.println(sb1 .equals(sb2));
System.out.println(sb1 .equals(ss1));
System.out.println("Poddar".subString(3));
a) false
false
false
dar
b) false
true
false
Poddar
c) compiler error
d) true
true
false
dar
The given answer is a.
Doesn't StringBuffer don't have "==" or "equals()".....?
Thanks
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
== operator compares the references
In the given program, sb1 and sb2 are referring to different objects.
So, sb1 == sb2 is false.
String and StrinBuffer both have equals() method that compare two encapsulated strings.
The StringBuffer class inherits its equals() method from Object, so the method does not perform expected behavior, which would be chracter by character comparison.
And you cannot compare String to StrinBuffer.

If I am wrong, anyone can correct me.....
Sachin Kombrabail
Greenhorn

Joined: Aug 28, 2000
Posts: 14

-> sb1 == sb2 is false Since the object references will be will be compared
-> sb1.equals(sb2) is false since StringBuffer does not have an equals method so the Object's equals method will be called (which does a comparision of the references)
-> sb1.equals(ss1) is false. for the same reason as sb1.equals(sb2)
-> "Poddar".subString(3) will give you "dar" provided you spell subString(3) with a lowercase 's' as substring(3).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String Buffer