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 ?
You need to precede this block with the word
staticto 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 ofitemobjectis created, which never happens in your code.