wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes NullPointer exception while printing array elements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NullPointer exception while printing array elements" Watch "NullPointer exception while printing array elements" New topic
Author

NullPointer exception while printing array elements

Rajiv Rai
Ranch Hand

Joined: Jun 14, 2010
Posts: 57


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

Joined: Jul 19, 2010
Posts: 142

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.


Life is full of choices. Sometimes you make the good ones, and sometimes you have to kill all the witnesses.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

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

Joined: Jun 14, 2010
Posts: 57





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

Joined: Apr 06, 2010
Posts: 4343
    
    8

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

Joined: Jun 14, 2010
Posts: 57
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
 
 
subject: NullPointer exception while printing array elements
 
Similar Threads
How to stop and start existing application in tomcat
Getting Session on web service client
Table Viewer GUI from a Database
SQL error
A fatal error has been detected by the Java Runtime Environment: ADT Eclipse