-1
class Book {
    String name;
    String author; 
}
class BookTest {

    public static void main(String[] args) {
         
        Book[] books = new Book[2];

        books[0].name = "The graps";
        books[0].author = "Siffyu";
        
        
        books[1].name = "Nova supreme";
        books[1].author = "Jagga";

        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i].name + ": " + books[i].author);
        }

    }
}

I tried creating an array that can hold Book type object. Once I created the array, I then initialized the book objects inside the array and tried to print them. I got NullPointerException instead.

user2340612
  • 10,053
  • 4
  • 41
  • 66
Vijay
  • 1
  • 1
  • Are you, by any chance, accustomed to programming in a language that has value (stack-allocated) objects? In java, everything besides simple types has reference semantics. That is, you need to first assign `book[0] = new Book()` and `book[1] = new Book()`, otherwise they are simply `null` references. – crizzis Aug 10 '23 at 10:29

1 Answers1

1

You forgot to instantiate the Book object : books[1] = new Book();

public static void main(String[] args) {
        
        Book[] books = new Book[2];
        
        books[0] = new Book();
        books[0].name = "The graps";
        books[0].author= "Siffyu";
        
        books[1] = new Book();
        books[1].name = "Nova supreme";
        books[1].author = "Jagga";

        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i].name + ": " + books[i].author);
        }

    }
rghome
  • 8,529
  • 8
  • 43
  • 62
DEV
  • 1,607
  • 6
  • 19