I am learning java and I'm doing an activity where I am using two different classes:
BookList (it contains a list of books). (capacity, numElements, books[])
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!