Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer Q

 
Kedar Dravid
Ranch Hand
Posts: 333
  • 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
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic