user253938
user253938

Reputation: 172

NullPointerException java error

i'm still starting to Learn OOP and there is this error that keeps popping out in my code; says that Exception in thread "main" java.lang.NullPointerException

public class SlumbookDriver{
    public static void main(String args[]){
       Slumbook[] contacts = new Slumbook[19];
       ... // index is an int and is the value of the index of the array
       ... // i feed it to a function "void viewEntry" that just shows
           // the other attributes of the class Slumbook
       viewEntry(index, contacts);
    }
 }

then i have the function viewEntry

public static void viewEntry(int index, Slumbook[] contacts){
    Scanner sc = new Scanner(System.in);
    if(index == 0){
        System.out.println("Array is empty");
    }
    else{
        String id = contacts[index].getIdNo();
        System.out.println("Please enter ID number");
        String idNo = sc.next();    
        if(id != idNo){
            while(id != idNo && index != -1){
                index--;
                id = contacts[index].getIdNo();
            }
            if(index == -1){
                System.out.println("ID does not exist");
                return; //terminate action since the ID number does not exist
            }
        }   
        System.out.println(contacts[index].viewDetails());
    }
}

Upvotes: 0

Views: 69

Answers (3)

OscarRyz
OscarRyz

Reputation: 199333

A NullPointerException happens when you try to access a field or a method in a reference but that reference is null.

For instance

Slumbook a = null;
a.getIdNo(); // NullPointerException

Same happens if you have an array

Slumbook [] data = new Slumbook[N];
data[i].getIdNo(); /// NPE

The second example would throw NPE if the reference contained at position i happens to be null.

When you get an exception a stack trace is shown and it contains the file name and exact line number(most of the times) where the exception occurred

Upvotes: 0

TheBigShaneyM
TheBigShaneyM

Reputation: 21

The problem here is that you have initialized an array of SlumBook, however the contents of the array need to be initialized. For starters, just initialize the contents:

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

Do this before using contacts in the method viewEntry(int, SlumBook[])

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

You are just initializing the array

   Slumbook[] contacts = new Slumbook[19];

but not its elements hence you will get a NullPointerException when you access the array element in statements like this:

    String id = contacts[index].getIdNo();

When you create an array of objects, the objects within the array are not initialized, you need to initialize them using new operator before using them. Something like this:

   contacts[index] = new Slumbook();

Upvotes: 2

Related Questions