• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 427
  • Last Modified:

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);
0
dpalyca755
Asked:
dpalyca755
6 Solutions
 
for_yanCommented:
StringBuffer buff = null;

buff.append()

if you invoke any method  anything on null that causes nullpointre
0
 
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
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now