简体   繁体   中英

Null Pointer Exception while using objects as array

This is my EmpData Class:

package com.bank;

public class EmpData {
int id;
String name;
String date;
String pos;
String status;


public void setEmp(int id, String name, String date) {
    this.id = id;
    this.name = name;
    this.date = date;
}

public void setStat(String pos, String stat){
    this.pos = pos;
    this.status = stat;
}

public void disp(){
    System.out.println(id+" : "+name+" : "+date+" : "+pos+" : "+status);
}

}

This is my Main Class:

package com.bank;

public class Bank {
    public static void main(String[] args) {
        EmpData[] obj = new EmpData[4];
        obj[1].setEmp(1, "Test123", "09-04-1990");
        obj[1].setStat("clerk", "on-hold");
        obj[1].disp();
    }
}

i got no syntax error in eclipse, but when i run the program i get the following null pointer error

Exception in thread "main" java.lang.NullPointerException at com.bank.Bank.main(Bank.java:6)

You are not initializing obj[1] before setting values..

as it should be

obj[1] = new EmpData();
obj[1].setEmp(1, "Test123", "09-04-1990");
obj[1].setStat("clerk", "on-hold");
obj[1].disp();

You didn't initialize obj[1], you just allocated 4 slots for EmpData, you create a new instance on each one. Just add this after you create your array:

obj[1] = new EmpData();

Create an instance of EmpData, set data to it and THEN assign it to the desired index. You are trying to assign values to NULL.

You have to fill your array with objects, what you have done is declaring the array and it's size.

public static void main(String[] args) {
        EmpData[] obj = new EmpData[4];
        obj[1] = new EmpData();        
        obj[1].setEmp(1, "Test123", "09-04-1990");
        obj[1].setStat("clerk", "on-hold");
        obj[1].disp();
}

You could also do

for (int i = 0; i < obj.length ; i++) {
    obj[i] = new EmpData();
}

to initialize them all with empty data. You could add a constructor to EmpData so you can set the data on creation of it.

You must first create a new object EmpData [] obj = new EmpData [4]; obj [1] = new EmpData ();

package com.bank;

public class Bank {
    public static void main(String[] args) {
        EmpData[] obj = new EmpData[4];
        obj[1] = new EmpData ();
        obj[1].setEmp(1, "Test123", "09-04-1990");
        obj[1].setStat("clerk", "on-hold");
        obj[1].disp();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM