• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Can someone explain why following code will throw npe

 
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I am not understanding why following code will throw npe, can someone explain.



Thanks
 
Sheriff
Posts: 3064
12
Mac IntelliJ IDE Python VI Editor Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, please UseCodeTags (⇐Click) when posting code samples. That makes them much easier to read.

You're seeing a weird artifact of autoboxing. Because Integer.parseInt() returns an int, Java decides the whole expression should have the type int, so it tries to unbox t.abc. Unboxing a null will give you an NPE every time. If you changed Integer.parseInt(strA) to Integer.valueOf(strA), which returns an Integer, then the whole expression would be of type Integer. In that case, Java would not try to unbox t.abc, and everything would work fine.
 
Padma Asrani
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot for explanation, my problem is resolved after I changed it to a Integer.valueOf()

Thanks
Padma

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic