views:

355

answers:

8

here is my code:

Comic[] comix = new Comic[3];  
comix[0] = new Comic("The Amazing Spider-man","A-1","Very Fine",9240.00F);  
comix[0].setPrice((Float)quality.get(comix[0].condition));  
for(int i=0;i<comix.length;i++){  
    System.out.println("Title: " + comix[i].title);  
}

Why am I getting a NullPointerException when this code runs?

+12  A: 

You're only setting the value of comix[0], but you're fetching comix[1].title and comix[2].title in the loop as well, as comix.length is 3. The default value for each element in an array of reference types is null. The length is the length of the entire array, not just the "populated" elements.

You may find List<T> (the most commonly used implementation being ArrayList<T>) easier to work with.

Jon Skeet
7 votes in two minutes--not bad at all.
Michael Myers
The only thing that would explain how fast (and well) Jon is answering questions is if he is creating a ton of alts to ask the questions in the first place... :D
John Gardner
+3  A: 

Because you've only defined what is inside comix[0], not comix[1] or comix[2]

Joseph
+2  A: 

Looks like you're only assigning the first of three objects and then displaying info about all three?

Gabri van Lee
+2  A: 

Because your for-loop iterates 3 times, as the Array size is 3. It doesn't matter if the array is filled with 3 elements or not, it's size is 3 nevertheless.

Michael Barth
+1  A: 

comix[1].title and comix[2].title are null. You can't println a null string.

rein
+2  A: 

Well, you declared an array that fits 3 instances of Comic and you only have one. So on the second iteration of your loop, comix[1] is null so comix[1].title throws NPE.

Chochos
+1  A: 

You defined comix as new Comic[3], so I'd expect Java to be going through the loop three times. On the second iteration, comix[1], there is no title.

David Thornley
actually there is no Comic...
Chochos
A: 

On line 3 you call quality.get... Is quality a variable defined somewhere else in this scope? Or is it a static class?

Jato