Results 1 to 2 of 2

Thread: Beginner Error

  1. #1
    Join Date
    Aug 2011
    Rep Power

    Default Beginner Error

    I'm learning Java and have come across my first problem that I can't figure out. The program runs but does nothing and gives an error.
    The 'error' is this:

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at books.BooksTestDrive.main(
    Java Result: 1
    BUILD SUCCESSFUL (total time: 0 seconds)

    Here is my code:

    Java Code:
    package books;
    public class Books {
        String title;
        String author;

    Java Code:
    package books;
    public class BooksTestDrive {
        public static void main(String[] args) {
            Books[] myBooks = new Books[3];
            int x = 0;
            myBooks[0].title = "The Grapes of Wrath";
            myBooks[1].title = "The Great Gatsby";
            myBooks[2].title = "Game of Thrones";
            myBooks[0].author = "Jason";
            myBooks[1].author = "Susan";
            myBooks[2].author = "Dily";
            while (x < 3){
                System.out.print(" by ");
                x += 1;
    Any help would be great! Thank you.

  2. #2
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Bali, Indonesia
    Rep Power

    Default Re: Beginner Error

    The declaration of Books[] myBooks = new Books[3]; only create an array of Book. But each element of this array still referencing a null. Because you've never instantiate a Book class for each of this array elements. So when you try to access myBooks[0] this will return you null. That is why you get a NullPointerException when you try to access a title from a null.

Similar Threads

  1. Replies: 2
    Last Post: 07-19-2012, 07:00 PM
  2. Beginner Help Please
    By cvh1717 in forum New To Java
    Replies: 1
    Last Post: 06-02-2012, 04:42 PM
  3. beginner
    By Eiolvit in forum New To Java
    Replies: 4
    Last Post: 07-10-2011, 05:32 PM
  4. Replies: 2
    Last Post: 03-12-2011, 02:14 PM
  5. beginner please
    By shroomiin in forum New To Java
    Replies: 6
    Last Post: 09-15-2009, 11:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts