File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer Q

 
Kedar Dravid
Ranch Hand
Posts: 333
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1258
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic