This week's book giveaway is in the OCAJP forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer Q 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 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer Q" Watch "StringBuffer Q" New topic

StringBuffer Q

Kedar Dravid
Ranch Hand

Joined: May 28, 2004
Posts: 333
Consider the code below:

class Q53
public static void main(String [] args)
java.lang.StringBuffer sb; //1
sb = new java.lang.StringBuffer().append("Hello").append("World"); //2
System.out.println(sb. substring(5,10).toString());

O/p: World

My question: Isn't sb initialised to null on Line 1?
So, by the end of line 2, isn't content of sb "nullHelloWorld"?
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Negative, blue leader!

Remember that automatic (a.k.a. local) variables are not initialized when declared, as member and class variables are. So, though you've declared it, it isn't even null (it's undefined). Furthermore, new StringBuffers start out with an empty buffer, not a buffer of "null". So, new StringBuffer().toString().equals("") would return true.

I agree. Here's the link:
subject: StringBuffer Q