-1

Hey can someone please help me understand why I keep getting a null pointer exception while trying to run this? I was just trying to learn arraylist for a course I am taking.

////////////////////////////////////////////

public class Address {
    int houseNumber;
    String roadNumber;
    String areaName;
    String cityName;


public Address(int hn, String rn, String an, String cn){
    this.houseNumber = hn;
    this.roadNumber = rn;
    this.areaName = an;
    this.cityName = cn;
}


public String toString() {
    return "House # " +  this.houseNumber + "\nRoad # " + this.roadNumber + "\n" + this.areaName + "\n" + this.cityName; 
}



}

/////////////////////////////////////////////////

import java.util.ArrayList;

public class AddressReferences {

ArrayList<Address> myCollection = new ArrayList<Address>();


public void addAddress (int hn, String rn, String an, String cn) {
    myCollection.add(new Address(hn,rn,an,cn));
}

public void printAddress () {
    for ( Address i : myCollection){
        System.out.println (i);


    }
}
}

//////////////////////////////////////

public class Test {

static AddressReferences ar;


public static void main(String[] args){

    ar.addAddress(46, "9/a", "Kotol", "Dhaka");
    ar.addAddress(44, "9/a", "Kotol", "Dhaka");
    ar.addAddress(28, "9/a", "Kotol", "Dhaka");
    ar.addAddress(89, "12/a", "Kotol", "Dhaka");
    ar.addAddress(60, "7/a", "Kotol", "Dhaka");


    ar.printAddress();





}
}
MooMoo
  • 39
  • 1

2 Answers2

3

Fields (instance fields or static fields) are initialized to the "all bits off" version of the kind of value they can hold; for object references, that's null. Your ar static field starts off with null, and you never assign anything to it. Thus, ar.addAddress(...) will throw an NPE, because ar is null.

To fix it, add

ar = new AddressReferences();

...to main before using ar for anything.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Here the null point exception doesn't mean myCollection is null, it means ar is null, so add ar = new AddressReferences(); into your main function.

public static void main(String[] args){

    ar = new AddressReferences();

    ar.addAddress(46, "9/a", "Kotol", "Dhaka");
    ar.addAddress(44, "9/a", "Kotol", "Dhaka");
    ar.addAddress(28, "9/a", "Kotol", "Dhaka");
    ar.addAddress(89, "12/a", "Kotol", "Dhaka");
    ar.addAddress(60, "7/a", "Kotol", "Dhaka");

    ar.printAddress();

}
Jerry Z.
  • 2,031
  • 3
  • 22
  • 28