2

Does anybody know why i can't append a char to this StringBuffer array (in my example below) and can somebody please show me how i needs to be done?

public class test {
    public static void main(String args[]){

        StringBuffer[][] templates = new StringBuffer[3][3];

        templates[0][0].append('h');
    }
}

My output to this code is:

output:     Exception in thread "main" java.lang.NullPointerException
            at test.main(test.java:6)

It would help me so much so if you know any solution, please respond to this

1
  • Code works as designed. Commented Feb 5, 2014 at 16:04

3 Answers 3

3

Below statement will just declare an array but will not initalize its elements :

    StringBuffer[][] templates = new StringBuffer[3][3];

You need to initialize your array elements before trying to append the contents to them. Not doing so will result in NullPointerException

Add this initialization

    templates[0][0] = new StringBuffer();

and then append

    templates[0][0].append('h');
Sign up to request clarification or add additional context in comments.

Comments

1

You need to initialize the buffers before you append something

templates[0][0] = new StringBuffer();

Comments

0

Others correctly pointed out the correct answer, but what happens when you try to do something like templates[1][2].append('h');?

What you really need is something like this:

public class Test {          //<---Classes should be capitalized.

    public static final int ARRAY_SIZE = 3;  //Constants are your friend.

    //Have a method for init of the double array
    public static StringBuffer[][] initArray() {
       StringBuffer[][] array = new StringBuffer[ARRAY_SIZE][ARRAY_SIZE];
       for(int i = 0;i<ARRAY_SIZE;i++) {
            for(int j=0;j<ARRAY_SIZE;j++) array[i][j] = new StringBuffer();
        }
        return array;
    }

    public static void main(String args[]){

       StringBuffer[][] templates = initArray();

        templates[0][0].append('h');
        //You are now free to conquer the world with your StringBuffer Matrix.
    }
}

Using the constants are important, as is is reasonable to expect your matrix size to change. By using constants, you can change it in only one location rather then scattered throughout your program.

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.