Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can someone explain why following code will throw npe

 
Padma Asrani
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

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



Thanks
 
Greg Charles
Sheriff
Posts: 2985
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks a lot for explanation, my problem is resolved after I changed it to a Integer.valueOf()

Thanks
Padma

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic