Search code examples
javaarraysnullpointerexception

How to fix java.lang.NullPointerException when trying to load a 2d object array in intelij


I have made a class with getter and setter methods, setting up one object was easy but as soon as I tried to set array it started giving me NullPointerException.

this is a function that I tried using to fill up the list:

public static void LoadKorisnike (int id, String ime, String prezime, String sifra){
    ListaKorisnika[id].setSifra(sifra);
    ListaKorisnika[id].setUserName(ime+prezime+Integer.toString(id));
    ListaKorisnika[id].setIme(ime);
    ListaKorisnika[id].setPrezime(prezime);
};

and here is the example of a set method:

public void setIme(String ime) {
    Ime = ime;
}

Solution

  • lacking a bunch of context, but most likely you haven't inserted a object at [id] yet, that's why you get a nullpointer exception there. Try first calling

    ListaKorisnika[id] = new YourClass();
    

    before you start with the setters.