mikjryan
mikjryan

Reputation: 11

Printing Object Values In Java

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

Answers (2)

zetafish
zetafish

Reputation: 2412

From your code snippet I assume that you think you are trying to do the following:

  • Declare an array of items
  • Initialize the the first two items with Toy objects
  • Get the first item of the array and print it

The problem in the code is:

  • You declare items array as static field
  • You have an instance initialization block where you initialize the array
  • You have a main function where you get the item and print it

The 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

Louis Wasserman
Louis Wasserman

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

Related Questions