Jesse Lesperance
Jesse Lesperance

Reputation: 85

Why am I getting a NullPointerException in this for loop?

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?

Upvotes: 0

Views: 1514

Answers (8)

nagaraju
nagaraju

Reputation: 31

You won't get an error, if you do like this:

Comic[] comix = new Comic[3];      

for(int i=0; i<comix.length; i++){

    comix[i] = new Comic[i];

    comix[i] = new Comic("The Amazing Spider-man","A-1","Very Fine",9240.00F);

    comix[i].setPrice((Float)quality.get(comix[0].condition));   

    System.out.println("Title: " + comix[i].title);   
} 

Upvotes: 1

David Thornley
David Thornley

Reputation: 57046

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.

Upvotes: 1

Chochos
Chochos

Reputation: 5159

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.

Upvotes: 2

rein
rein

Reputation: 33455

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

Upvotes: 1

Michael Klement
Michael Klement

Reputation: 3414

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.

Upvotes: 2

Gabri van Lee
Gabri van Lee

Reputation: 135

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

Upvotes: 2

Joseph
Joseph

Reputation: 25523

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

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502006

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.

Upvotes: 12

Related Questions