Ocasta Eshu
Ocasta Eshu

Reputation: 851

ArrayList.add() method causing NullPointerException

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?

Upvotes: 4

Views: 24004

Answers (2)

Tony
Tony

Reputation: 1419

You need to create your storedStrings variable before using it.

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

Upvotes: 3

Kirk Woll
Kirk Woll

Reputation: 77546

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.

Upvotes: 19

Related Questions