Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

NullPointerException error  RSS feed

 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I've got code that compiles fine, but gives a NullPointerException error when I try to run it. Specifically, it says:

Exception in thread "main" java.lang.NullPointerException
at mrchen.ButtonDrawPanel.<init>(rktest.java:884)
at mrchen.rktest.<init>(rktest.java:21)
at mrchen.rktest.main(rktest.java:901)

This happened when I changed my code from using a 2D array of strings


to a 2D array of "Square" objects:


Of course, I made a bunch of other changes to support this as well (method calls to get the String out of the object, for instance), and everything compiled fine, but like I said - when I run it, I get this NullPointerException error.

Any suggestions of common code errors that produce this sort of thing?

Thanks,
Mike
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create any array with objects in it, those objects will not be automatically initialized; basically, after creating that array, you have a 2D array with each of the 81 values being null.

Just initialize them all in a nested loop, and your error should be gone.
 
Raghavan Muthu
Ranch Hand
Posts: 3389
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What i would think is have you really had some objects into an array? Because what you have posted is just an array declaration -a placeholder.

The following code shows how an array should really be dealt in a program. Its for an 1D array of Square objects.



You can even initialize them in a loop provided if all them are initiated with similar kinda objects.
 
MR Chen
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob and Raghavan -

Thanks for the help with this!

I had just realized that this was the problem (i.e. Square array with no Square objects), but I'm glad to have confirmation from more experienced hands.

Much appreciated,
Mike
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!