• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

NullPointer exception while printing array elements

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


When executing this code it throws the following error

Exception in thread "main" java.lang.NullPointerException
at com.rajiv.ArrayTest2.main(ArrayTest2.java:14)


Can't figure out why it throws this error?
Please help

Thanks
 
Jan Hoppmann
Ranch Hand
Posts: 147
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a tricky one. When you use a for-each-loop, Java creates copies of the objects that you manipulate. That means, that you don't really create new objects in your first loop (well, you do, but they don't go into the array). You should try this with an old-fashioned for loop with a counter variable.
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't update an array using the enhanced for loop like that. What you've got is a rough equivalent of:
Given that, can you see why you aren't actually putting any books in the array at all? So on line 13, you've got an array full of null values.
 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





According to SCJP book both the above code snippets are equivalent

Now due the error received above , can i assume that both code snippets
are not equivalent?
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where does it say that? They're definitely not equivalent. In the first case you're adding a Dog reference into an array, and in the second you're assigning a Dog reference to a variable. But I suspect the example in your book may have been different. If you aren't assigning to those variables, other operations are equivalent.
 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well its given in SCJP 5 book but i just checked an ebook of SCJP 6
and in the SCJP 6 book they have modified it

So may be it was an error in the SCJP5 book
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic