Push objects into array in Java Exception in thread “main” java.lang.NullPointerException

I’m learning Java and I stuck on this example

This is the main

package bookstore;

public class BookStore {


    public static void main(String[] args) {
        // create a Book object

        Book Java = new Book();
        Book Python = new Book();
        Book PHP = new Book();

        Java.name =  "Thinking In Java";
        Java.author = "Ahmad Ajmi";
        Java.canBorrow = true;
        Java.canReturned = true;
        Java.pagesNumber = 400;
        Java.publisher = "Oriely";
        String publish = Java.publishedDate(2013,4,5);

        System.out.println(publish);

        // Library.booksNumber works fine
        System.out.println("You have " + Library.booksNumber + " Books");

        // The problem is here
        System.out.println(Library.books);

    }
}

Book Class

package bookstore;

public class Book {

    // Defining book variables
    String name;
    String author;
    String publisher;
    int pagesNumber;
    int publisheddate;
    boolean canBorrow;
    boolean canReturned;

    public String publishedDate(int year, int month, int day) {
        return "" + year + " - " + month + " - " + day;
    }

    Book () {

        // Keep track of books created  
        Library.booksNumber += 1;

        // Here I want to push the book name into array
        for (int i = 0; i < Library.booksNumber; i++) {
            Library.books[i] = name;
        }

    }


}

Library Class

package bookstore;

public class Library {

    static int booksNumber;

    // Array to push book names
    static String[] books;    

}

When I run I get this error

Exception in thread "main" java.lang.NullPointerException
    at bookstore.Book.<init>(Book.java:23)
    at bookstore.BookStore.main(BookStore.java:9)
Java Result: 1

I want to push books names into the Library.books array

Answer

You need to initialize books array.
try this in Book class

Library.books = new String[Library.booksNumber];
for (int i = 0; i < Library.booksNumber; i++) {
        Library.books[i] = name;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *