0

I am learning java and I'm doing an activity where I am using two different classes:

  1. BookList (it contains a list of books). (capacity, numElements, books[])

  2. Book (it contains the properties of each book). (id, title, editorial...)

Inside the class BookList, I have a method named findByEdithorial():

public BookList findByEdithorial(String edithorial) {
    //BookList bookList2 = null;
    BookList bookList2 = new BookList(numElements);

    for (int i = 0; i < numElements; i++) {
        int add;
        if(edithorial.equals(books[i].getEdithorial()))
        {
            bookList2.add(books[i]);

        }
    }        
    return bookList2;
}

And what I am doing here is that the method receives the editorial and then I compare if it exists (in my actual array of books "books"), and if it exists, I add the Book object to bookList2.

My question is that when I use:

BookList bookList2 = new BookList(numElements);

the program runs without any problem, but when I try:

BookList bookList2 = null;

it throws me:

Exception in thread "main" java.lang.NullPointerException
    at shop.BookList.findByEdithorial(BookList.java:92) 

I know that I can't do it this way because the compilator is telling me it, but I don't know why the compilator does not like this one way.

Can you please explain me why is it wrong?

Thank you!

Jordi 45454
  • 275
  • 2
  • 3
  • 11
  • it is a dup, isn't it? OP, please check on internet, what is java's NullpointerException – Kent Dec 14 '15 at 19:47
  • " the compilator is telling me it" This is not the compiler telling you this, it is a runtime error. `null` is for a value which is not initialised and you can't dereference a reference which hasn't been initialise to point to an object as there is no object to use. – Peter Lawrey Dec 14 '15 at 20:17
  • I think that I've got it. I can declarate a null object if and only if I assing to it a value (object) with "=". And if I use ClassName className = new Class(property) I am able to use the methods and properties of this object. So if I declare a null object, when I assing a value (object) to it, then I am able to use it as an object. // Thank you and sorry to open a duplicate post. I thought my question was not so general. – Jordi 45454 Dec 14 '15 at 20:43

0 Answers0