Reputation: 223
I am trying to create static array which i initialize later in the method
Something like this
static Object[][] table;
static Object[] codeZero;
static Object[] codeOne;
I call this method from main
static void init(){
table = new Object[][]{codeZero,codeOne};
}
and then in another method i try something like this
codeZero=new Object[2];
codeOne=new Object[2];
table[0][0]= new Integer(4);
when i try to print table[0][0] it gives me a null pointer exception
Upvotes: 0
Views: 66
Reputation: 85779
This is what's hapenning
Instantiating table
variable with null
elements:
table = new Object[][] { codeZero, codeOne };
Change the references of codeZero
and codeOne
variables, the old references will still remain in table
, they won't be replaced.
codeZero = new Object[2];
codeOne = new Object[2];
Since the old null
references are still in table
, you will get a NullPointerException
when calling table[0][<whatever>]
.
Possible fix: Initialize codeZero
and codeOne
before initializing table
. Then, initialize table
using your currently approach:
codeZero = new Object[2];
codeOne = new Object[2];
table = new Object[][] { codeZero, codeOne }
Upvotes: 3