ArrayList returning NullPointer Exception || Java || OOP -


this question has answer here:

hey can please me understand why keep getting null pointer exception while trying run this? trying learn arraylist course 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 () {     ( address : 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();      } } 

fields (instance fields or static fields) initialized "all bits off" version of kind of value can hold; object references, that's null. ar static field starts off null, , never assign it. thus, ar.addaddress(...) throw npe, because ar null.

to fix it, add

ar = new addressreferences(); 

...to main before using ar anything.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -