GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Can someone explain why following code will throw npe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can someone explain why following code will throw npe" Watch "Can someone explain why following code will throw npe" New topic
Author

Can someone explain why following code will throw npe

Padma Asrani
Ranch Hand

Joined: Mar 22, 2007
Posts: 111
Hi

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



Thanks
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2853
    
  11

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

Joined: Mar 22, 2007
Posts: 111
Thanks a lot for explanation, my problem is resolved after I changed it to a Integer.valueOf()

Thanks
Padma

 
GeeCON Prague 2014
 
subject: Can someone explain why following code will throw npe