1

so I'm learning Java for the first time. The following code throws a NullPointer exception when square.toString() is called in another class (where square is an instance of the object defined in this class), and I'm a little foggy about why this doesn't work. Can someone explain that to me?

public class SquareBuilder { String box; String[] parts; final private String beam = "----"; final private String collumn = "|"; private int size; public SquareBuilder(int firstSize) { size = firstSize; } public static String repeatString(String s, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(s); } return sb.toString(); } public void changeSize(int newSize) { size = newSize; } public String toString( ) { parts[0] = repeatString(beam,size) + "\n"; parts[1] = collumn + repeatString(" ",4*size-2) + collumn + "\n"; box = parts[0] + repeatString(parts[1],size-2) + parts[0]; return box; } } 
1
  • 3
    What's the full stack trace of your exception? Commented Mar 2, 2013 at 21:56

3 Answers 3

3

It's unclear why you've declared an instance variable called parts which you then dereference (parts[0] = ...) in toString() - but you're never initializing it, so the value is null... hence the exception.

Why is your implementation not just:

public String toString( ) { String ends = repeatString(beam,size) + "\n"; String middle = collumn + repeatString(" ",4*size-2) + collumn + "\n"; return ends + middle + ends; } 

It's very unusual to want to modify an object in toString().

Sign up to request clarification or add additional context in comments.

1 Comment

I had arrays on the brain for some reason, obviously no reason to use them. Thanks.
1

Your question is not framed properly, however i guess that you are getting an NPE in your toString() method. Reason is you never really initialized your array String[] parts; in your code.

You have to initialize it first:

public SquareBuilder(int firstSize) { size = firstSize; this.parts = new int[give the size here]; } 

Comments

0

A NullPointerException comes when you attempt to use methods on a null object. You should, in your constructor, initialize the parts array using the expression

parts = new String[whateverSizeYouWant];

It is not clear to me what you are doing with the array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.