This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on string/stringbuffer

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Thanks!

 
zhaobin74
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kishan Kumar
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
------------------
Regards,
V. Kishan Kumar
 
Vivek Nambiar
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please go though this link, it helps u in understanding it further...
http://www.javaranch.com/ubb/Forum24/HTML/000530.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic