my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Autoboxing and unboxing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Autoboxing and unboxing" Watch "Autoboxing and unboxing" New topic
Author

Autoboxing and unboxing

Prav sharma
Ranch Hand

Joined: Feb 07, 2005
Posts: 102
Hi

I created the below code to use the autoboxing feature and expected to run properly but instead it gave Exception



Can anybody explain?



[HENRY: Formatted Code]
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9321
    
  17

This line would create the exception

x=i+y;

This is the first line of the constructor and you have not initialized the Integer variable i so it's value will be null. Then unboxing will try to call i.intValue() on this which will result in a NullPointerException...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sachin Adat
Ranch Hand

Joined: Sep 03, 2007
Posts: 213
Its a NPE.
Instance variable i is initialized to null.


SCJP 6
How To Ask Questions On Java Ranch - How To Answer Questions On Java Ranch
Prav sharma
Ranch Hand

Joined: Feb 07, 2005
Posts: 102
Oh Great. So to sum up it means that we can't convert null to 0 through unboxing.

Thanks Guys !!!
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Prav sharma wrote:Oh Great. So to sum up it means that we can't convert null to 0 through unboxing.

Thanks Guys !!!


For unboxing, IntegerObject.intValue() is called, so here i.intValue() is called that is actually null.intValue(). So NPE.


SCJP 6
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Autoboxing and unboxing