4

The class LongInteger is causing the following error when run:

Exception in thread "main" java.lang.NullPointerException
at LongInteger.breakString(LongInteger.java:38)
at LongInteger.<init>(LongInteger.java:17)
at LongInteger.main(LongInteger.java:149)

Here are some relevant class excerpts:

public class LongInteger extends Object {
private ArrayList<String> storedStrings;          


  // Constructor
 public LongInteger(String s) {
    this.setInputString(s);
    this.breakString(this.inputString);       //Exception @ line 17
}

 /**
  * the purpose of this method is to break the input string into an 
  * ArrayList<String> where each String has a length of 9 or less.
  */
 private void breakString(String s){         
    if(s.length()>9){
        storedStrings.add(0,s.substring(s.length()-9,s.length()));
        this.breakString(s.substring(0,s.length()-9));
    } else {
        this.storedStrings.add(0,s);        //Exception @ line 38
    }
 }


public static void main(String[] args) {
    LongInteger a = new LongInteger("12345");   //Exception @ line 149
    }
}

I am at a loss as to what is causing this NullPointerException. Anyone have a suggestion?

1
  • Is "storedStrings" ever initialized? Commented Feb 16, 2012 at 1:36

2 Answers 2

19

You never instantiate storedStrings. Try changing:

private ArrayList<String> storedStrings;

To:

private ArrayList<String> storedStrings = new ArrayList<String>();

When you have the line:

this.storedStrings.add(0,s);

It is invoking the method add on an instance of ArrayList<String> stored in this.storedStrings. The new operator is how you get new instances of things.

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

Comments

3

You need to create your storedStrings variable before using it.

ArrayList<String> storedStrings = new ArrayList<String>();

1 Comment

storedStrings was created, it just wasn't initialized.

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.