Two Laptop Bag
The moose likes Beginning Java and the fly likes please explain the output, comparing with String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "please explain the output, comparing with String" Watch "please explain the output, comparing with String" New topic

please explain the output, comparing with String

kumar Nagesh

Joined: Jan 02, 2007
Posts: 12

StringBuffer sb1 = new StringBuffer("Hello");
StringBuffer sb2 = new StringBuffer("Hello");
System.out.println("String Buffer False");
if (sb1 == sb2) {
Ankit Garg

Joined: Aug 03, 2008
Posts: 9435

Just go through the documentation of StringBuffer class. You will find that it doens't override the equals method. So the equals method of Object class is called which uses == for comparing the objects.

Now two StringBuffer objects don't refer to the same object even if they contain the same value. Each StringBuffer object created through the new syntax will always point to a different object. So using == on them will return false...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11882

It would help greatly if you would also put in your post what the output IS, and what you EXPECTED it to be. That let's other focus in on what your misunderstanding is, rather than guess on what your confusion is.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: please explain the output, comparing with String
It's not a secret anymore!