• Post Reply Bookmark Topic Watch Topic
  • New Topic

why it is throwing nullpointerexception?  RSS feed

 
amit grynch
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone tell me why this code is throwing nullpointerexception??
[Edit:Ended code tag at proper place]
 
manish ghildiyal
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...may be because while adding method is being called on i which is not initialized.

Manish
 
Patterson Silva
Greenhorn
Posts: 1
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The variable i is not initialized, then you can not sum it to y.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you declared i as an int then it would be initialised to 0, and so this would work fine. But you've declared it to be an Integer, which is a reference type and so it's initalised to null. Then on line 8 it is unboxed, but trying to unbox null will cause a NullPointerException.

I'm not sure why you're using new Test24(new Integer(4)) - simply new Test24(4) is clearer and has the same effect here.

And welcome to the Ranch!
 
Roshi Kumar
Greenhorn
Posts: 21
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int x; // it is a primitive type and default value assigned to it is 0 ; So you can use it in a expression;

Integer i; // it is a object here getting default value as NULL , so you can't operate on it before initializing as like all other objects
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!