Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 448
Ocasta Eshu Avatar asked Nov 29 '22 15:11

Ocasta Eshu


1 Answers

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.

like image 195
Kirk Woll Avatar answered Dec 04 '22 11:12

Kirk Woll