Saturday, August 7, 2010

Object References:

Courtesy of Head First Java, 2nd Edition (0596009208)
Page 63

This code compiles, but when you run it, the JVM outputs the following:

Exception in thread "main" java.lang.NullPointerException
    at BooksTestDrive.main(

myBooks is not an array of Books, it is an array of references to the object Books. Each index of myBooks must be assigned a Books object to refer to. Instead, the indices of myBooks refer to NULL, so when you try to assign a value to Books.title or the JVM gives a NullPointerException because in effect, you are assiging a value to something that does not exist

Below is the corrected code:

Lines 10, 12, and 14 assign the actual Books object to the references that are supposed to refer to Books in the first place!

No comments:

Post a Comment