0

So, I have this class, that contains another class array, and in the constructor I want to make "n" and "nCod" equal 0.

public class ITable
{   
TableRow arr[];

class TableRow
{
    long n;
    int nCod;
    ICode cod;

}

ITable()
{
    arr = new TableRow[256];
    for(int i=0;i<256;i++)
    {
        arr[i].n = 0;
        arr[i].nCod = 0;
    }
}
}

When I run it, Eclipse console tells me:

java.lang.NullPointerException
at jhuffman.def.ITable.<init>(ITable.java:21)

That line is:

arr[i].n = 0;

2 Answers 2

3

When you create an array instance with new TableRow[256], each of its elements are initialized to null.

Therefore, each element should be initialized before being accessed :

arr = new TableRow[256];
for(int i=0;i<256;i++)
{
    arr[i] = new TableRow (); // add this
    arr[i].n = 0;
    arr[i].nCod = 0;
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you create an object array with no initial values, all the positions in the array will point to null. So, for example, arr = new TableRow[3] would initialize the array as [null, null, null].

Since you did not store any TableRow objects into arr, when you access arr[i], it returns null instead of a concrete object. If you try to access a field in null it will result in a NullPointerException as you have observed.

What you need to do is create the TableRow instances and place them into the array before you try to access them. Something like this:

arr = new TableRow[256];
for (int i = 0; i < arr.length; i++) {
    arr[i] = new TableRow();
    arr[i].n = 0;
    arr[i].nCode = 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.