0

This program complies but won't run successfully, I am unable to find the bug.

public class Q1 {
    public static void main(String[] args) {
        StringBuffer[]stringBuffers = new StringBuffer[10];

        for(int i =0; i< stringBuffers.length;i++){
            stringBuffers[i].append("StringBuffer at index " + i);
        }
    }
}
2
  • 1
    NullPointerException... too trivial, try to read the stackbacktrace when the program finish Commented Oct 16, 2012 at 10:16
  • Please don't use StringBuffer if you can use StringBuilder. vanillajava.blogspot.co.uk/2012/08/… Commented Oct 16, 2012 at 10:23

4 Answers 4

6

You don't initialize your stringbuffers.

You should have something like

for(int i =0; i< stringBuffers.length;i++){
   stringBuffers[i] = new StringBuffer();

or

for(int i =0; i< stringBuffers.length;i++){
   stringBuffers[i] = new StringBuffer("StringBuffer at index " + i);
Sign up to request clarification or add additional context in comments.

1 Comment

Why do I suddendly, one month later, get my first downvote on this answer ? Did I anger somebody ?
2

You need to init the StringBuffer:

public class Q1 {
public static void main(String[] args) {
    StringBuffer[]stringBuffers = new StringBuffer[10];

    for(int i =0; i< stringBuffers.length;i++){
        stringBuffers[i]= new StringBuffer();
        stringBuffers[i].append("StringBuffer at index " + i);
    }
}
}

Comments

1

You need to initialize the StringBuffer objects in your array with the required String: -

for(int i =0; i< stringBuffers.length;i++){
    stringBuffers[i] = new StringBuffer("StringBuffer at index " + i);

}

Comments

1

IN the statement:

StringBuffer[]stringBuffers = new StringBuffer[10];

you have just created an array of 10 elements. But you have not put any element in it.Each element in this array is still empty and by default, contains null.

So when you called

stringBuffers[i].append("StringBuffer at index " + i);

here stringBuffers[i] is still uninitialized and is pointing to null.

So it is giving java.lang.NullPointerException.

As stated in other answers, if you do like this:

for(int i =0; i< stringBuffers.length;i++){
   stringBuffers[i] = new StringBuffer();

This will initialize each element of stringBuffer array with the reference to a StringBuffer object.So stringBuffer[i] now is not empty.


By the way You should use StringBuilder. Both StringBuffer and StringBuilder provides mutable strings. Use StringBuffer only if your application is running in multithreading environment becoz it introduces performance overhead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.