Reputation: 11
With the code
package items;
public class itemtest {
static itemobject[] item = new items[10];
{
items[0] = new Toy("Example ID","Example Desc");
items[1] = new Toy("Second Example ID", " Second Example Desc");
}
public static void main(String[] args)
{
String tid = items[0].exampleiD;
System.out.print(tid);
}
}
I get the error :
Exception in thread "main" java.lang.NullPointerException at items.itemtest.main(itemtest.java:17)
on the code line: String tid = item[0].exampleID;
Sorry I'm very new to java, could anyone shed some light on what I'm doing wrong ?
Upvotes: 0
Views: 259
Reputation: 2412
From your code snippet I assume that you think you are trying to do the following:
The problem in the code is:
static
fieldThe problem is that the initialization block is done at initialization of instances. The main method however is a static
method and has no instance. Therefore the block has not been called yet and you get a NPE.
You need to make the initialization block also static
like this:
static {
items[0] = new Toy...
items[1] = new Toy...
}
A static
initialization block is called once when the class is initialized. So that way it is called before main will be run.
Upvotes: 0
Reputation: 198033
{
items[0] = new Toy("Example ID","Example Desc");
items[1] = new Toy("Second Example ID", " Second Example Desc");
}
You need to precede this block with the word static
to have it take effect when the class is loaded -- which is what you actually want to happen, based on your code -- as opposed to when a new instance of itemobject
is created, which never happens in your code.
Upvotes: 2