• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why it is throwing nullpointerexception?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can anyone tell me why this code is throwing nullpointerexception??
[Edit:Ended code tag at proper place]
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
...may be because while adding method is being called on i which is not initialized.

Manish
 
Greenhorn
Posts: 1
Firefox Browser Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The variable i is not initialized, then you can not sum it to y.
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Greenhorn
Posts: 21
Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic