This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one 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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer Q" Watch "StringBuffer Q" New topic
Author

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.


Nathaniel Stodard<br />SCJP, SCJD, SCWCD, SCBCD, SCDJWS, ICAD, ICSD, ICED
 
 
subject: StringBuffer Q