user3075117
user3075117

Reputation: 49

how to handle NullPointerException in this code?

I am new at java and i have this exception in my code:

Exception in thread "main" java.lang.NullPointerException
    at Course.addStudents(Course.java:31)
    at Third.main(Third.java:28)

Course.java

public boolean addStudents(Student newStudent){
     for (Student student : students){
         if (student.getID()== newStudent.getID()){
             return false;
         }
     }
     if(numberOfStudents < capacity){    
         students[numberOfStudents++] = newStudent;
         return true;
     }
     return false;
     }

Third.java

c1.addStudents(s1);

I have tried the solve it but didnt achieve. I searched for it and I guess the problem is initializing. Is it true? if it is, I dont know how to handle with that, any idea??

Upvotes: 0

Views: 105

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122026

As per your comment

  for (Student student : students){

students is an array and not initialized.

Since you are using arrays , that initialization would be

Student[] students = new Student[capacity];

Remmeber that when you intialize an array ,default values will be null untill unless you fill them. In your loop you have to check for null as again it causes NullPOinterException

 for (Student student : students){   
         if (student !=null && student.getID()== newStudent.getID()){
             return false;
         }
     }

Upvotes: 3

Tal
Tal

Reputation: 700

the problem, is indeed initializing, one or more of the below is not initialized:

newStudent, students.

as Student is an object it needs an initialization before you can use it, as opposed to primitive types.

Upvotes: 2

Related Questions