Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Exception in thread "main" java.lang.NullPointerException

 
Greenhorn
Posts: 11
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've done a little research on my own and found that usually this happens when an object you are pointing at has no value.
I'm just having a little trouble understanding why this is happening here.

class Books {
String title;
String author;

}

class BooksTestDrive {
public static void main(String [] args) {

Books [] myBooks = new Books [3];

int x = 0;

myBooks[0].title = "The moon is a harsh mistress";
myBooks[1].title = "Hitchhikers guide to the galaxy";
myBooks[2].title = "Stranger in a Strange Land";
myBooks[0].author = "Heinlein";
myBooks[1].author = "Douglas Adams";
myBooks[2].author = "Heinlein";

while (x < 3) {

System.out.println(myBooks[x].title);
System.out.println("By");
System.out.println(myBooks[x].author);

x = x + 1;


}



}
}


Maybe there's something I'm missing or just not quite understanding but it compiles then when i run it gives me
Exception in thread "main" java.lang.NullPointerException
at BooksTestDrive.main(BooksTestDrive.java:8)




 
Bartender
Posts: 7208
65
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to UseCodeTags (<-- link). Without line numbers we can't tell where line 8 is. It also makes it easier to read.
 
Saloon Keeper
Posts: 12165
258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Print out the value of myBooks[0] before line 8.
 
Carey Brown
Bartender
Posts: 7208
65
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
myBooks[0].title = "The moon is a harsh mistress";
myBooks[0] is null because you haven't yet created a Book object.
myBooks[0] = new Book();
 
Marshal
Posts: 69894
278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this sort of thing:-If you do that before you have populated the array, you will see that elements in arrays have default initial values. They are the same as the initial values of fields (see link above/to left).
You might do well to use an array initialiser; there is an example (for ints) here. Please give the fields in your Book class (not Books, please) private access and initialise then via the constructor:-\u2019 is ’ a posh apostrophe.
 
Ranch Hand
Posts: 135
5
Eclipse IDE Postgres Database Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie's answer is correct. I'll explain a bit if you still didn't understand.



In the above line, it means, you created an Array which can hold 3 Books. That's all what this line means.

But you assume, the array do actually have 3 Books when you write that above line. This is wrong!

So, you must fill that empty myBooks array with Books objects
 
Ranch Hand
Posts: 218
5
MS IE Notepad Suse
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Jude Niroshan wrote:Campbell Ritchie's answer is correct. I'll explain a bit if you still didn't understand.



In the above line, it means, you created an Array which can hold 3 Books. That's all what this line means.

But you assume, the array do actually have 3 Books when you write that above line. This is wrong!

So, you must fill that empty myBooks array with Books objects


Let's abstract this a bit more:

@OP
Declaring a non-primitive array is pretty much like put four planks together to build a shelf. In your case you declare an array for a type Book - so, you build yourself a bookshelf. But: as in real world building or buying a bookshelf doesn't mean it already contains books - it's just the box around it. Same is true for your array: you declared a space wich CAN hold books, but tt doesn't contain any in the first place without you adding some, hence you get a NPE.

NPE always means somethig in that line is 'null' instead of something. As your line 8 is an assignment of an inner property of a book it's obvious that only the indexed array element can be the issue, otherwise you would had gotten a very different issue, maybe a compile time error.

So, before you can say: the first book has the title X and was written by Y, you have to put a book in that space. So, before calling books[x].title= to set the title (be aware, you access a private member directly, after you got the basics you should switch to encapsulation with setters and getters) you have to call books[x]=new Book() to "put a new book into place x".
 
Greenhorn
Posts: 1
Android Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create object for Books class and it's work for me.


       Books[] myBooks = new Books[3];
       int x = 0;

       myBooks[0] = new Books();
       myBooks[1] = new Books();
       myBooks[2] = new Books();

       myBooks[0].title = "The Grapes of Java";
       myBooks[1].title = "The Java Gatby";
       myBooks[2].title = "The Java cookbook";
       myBooks[0].author = "bob";
       myBooks[1].author = "sue";
       myBooks[2].author = "ian";
 
Campbell Ritchie
Marshal
Posts: 69894
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welome to the Ranch

If you had used the code button, as was suggested earlier, your code would have looked much better, like this:-Why are you declaring x in line 2? You aren't using it.

I would prefer an array initialiser if at all possible: it has the advantages that you can get rid of the nulls immediately, and the size of the array exactly matches its contents. No risk of any exceptions from the array indices.Please tell us the source of any code: that code looks familiar to me.
Please tell us why I think the lass should be called Book rather than Books.
Also tell us about the design error visible in that code.
 
Blood pressure normal? What do I change to get "magnificent"? Maybe this tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic