File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes question on string/stringbuffer 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 "question on string/stringbuffer" Watch "question on string/stringbuffer" New topic

question on string/stringbuffer

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
When comparing Strings and StringBuffers, which of the following statements evaluate correctly and return true:
a) new String("IBMVAJava") == new String("IBMVAJava")
b) new String("IBMVAJava").toString().equals(new String("IBMVAJava"))
c) new StringBuffer("IBMVAJava") == (new StringBuffer("IBMVAJava"))
d) new StringBuffer("IBMVAJava").equals(new StringBuffer("IBMVAJava"))

Can any one explain the answer here?


Joined: Sep 26, 2000
Posts: 6
b) is right. equals() compare the content of Strings.
Since "new" will create new objects and "==" compares 2 reference to see it they point to the same object,a) and c) are wrong.
I am not very clear why d) is wrong.

I eapect to pass SCJP2 test
Kishan Kumar
Ranch Hand

Joined: Sep 26, 2000
Posts: 130
d is wrong because the StringBuffer class does not override the
Object's equals method and hence only object references are compared as specified in the Object's equals method.
Hope this helps!
V. Kishan Kumar

Regards,<BR>V. Kishan Kumar
Vivek Nambiar
Ranch Hand

Joined: Sep 25, 2000
Posts: 63
Please go though this link, it helps u in understanding it further...
I agree. Here's the link:
subject: question on string/stringbuffer
It's not a secret anymore!