StringBuffer

why would the following sequence cause a null pointer exception on the append?


StringBuffer buff = null;
String line = null;

line = "<test>abc</test>";
buff.append(line);
dpalyca755Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:
StringBuffer buff = null;

buff.append()

if you invoke any method  anything on null that causes nullpointre
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:
StringBuffer buff = new StringBuffer("");


String line = "<test>abc</test>";
buff.append(line);
0
for_yanCommented:
You cannot invoke any method on null - that is exactly the meanning of null pointer execption - invocation of merthod on null
0
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

dpalyca755Author Commented:
If I plan to work with the StringBuffer and don't know the size do I need to set the capacity?
(I ask because I see the capacity defaulted to 16 characters).
0
for_yanCommented:
No you don't need to set caparity - you can start form empty string like I showed (not a null though but a string without any charcters!) and then append as much as you want
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
Or use the other constructor, new StringBuffer() which starts as an empty string.

However, are you using Java version 5 or above? And are you doing anything with Threads? If you are version >= 5 and NO threads, then use StringBuilder instead (as recommended in the Javadoc) as it will perform faster.
0
CEHJCommented:
then use StringBuilder instead (as recommended in the Javadoc)

That's correct. You can set the length of the StringBuilder when optimisation is required. Look into the inner workings of StringBuilder to see how to do that best
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.