Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Autoboxing and unboxing

 
Prav sharma
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Sachin Adat
Ranch Hand
Posts: 213
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its a NPE.
Instance variable i is initialized to null.
 
Prav sharma
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh Great. So to sum up it means that we can't convert null to 0 through unboxing.

Thanks Guys !!!
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic