Array null pointer exception error

后端 未结 2 866
甜味超标
甜味超标 2020-12-20 21:37

I am continuing with my project for school and have seemed to encounter another error. So what is happening is basically I am receiving a null pointer exception even though

相关标签:
2条回答
  • 2020-12-20 22:12

    As your code is currently written,

    System.out.println(studentArray[0].getFirstName());
    

    Will throw an NPE since you're never initializing the array.

    private static students[] studentArray;
    

    Just declares it, doesn't initialize it.

    Maybe you should refactor your code as follows

    private static ArrayList<students> studentArray = new ArrayList<students>();
    
    // Inside the constructor or some method called before you access studentArray:
    studentArray.add(stu1);
    studentArray.add(stu2);
    //...
    
    // or, more concisely, since you're not using the temporary `students` variables:
    studentArray.add(new students(65435, "Bob", "Ted"));
    studentArray.add(new students(45546, "Guy", "Sid"));
    //...
    

    If you're committed to using an array and not a List,

    private static students[] studentArray;
    

    needs to be initialized with something like

    private static students[] studentArray = new students[10];
    

    and then you need to assign its elements

    studentArray[0] = stu1;
    

    or

    studentArray[0] = new students(65435, "Bob", "Ted");
    
    0 讨论(0)
  • 2020-12-20 22:22

    You should always create a object before trying to access it. You have declared a reference pointing to a array :

    private static students[] studentArray;
    

    but never assigned any object to the reference. Hence you get a NullPointerException.

    Use this :

    private static students[] studentArray = new students[size]; 
    

    Above code will create a new object (array of students), pointed by a reference variable (studentArray). OR

    You can use List or Set which are more efficient then array.

    0 讨论(0)
提交回复
热议问题