Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd NullPointerException

Tags:

java

Stacktrace from my NPE starts with:

Caused by: java.lang.NullPointerException
    at pl.yourvision.crm.web.servlets.listExport.ProductListExport.writeCells(ProductListExport.java:141)

Line number 141 in this file is:

Double availablePieces = store != null ? store.getAvailablePieces() : 0.0;

Where store is not null and store.getAvailablePieces() is null. I do not understand why I get exception in here.

Any ideas?

like image 449
zimi Avatar asked Jan 23 '14 10:01

zimi


1 Answers

I'm 99% sure this is because of the behaviour of the conditional operator. I believe your code is equivalent to:

double tmp = store != null ? store.getAvailablePieces() : 0.0;
Double availablePieces = tmp;

In other words, it's unboxing the result of store.getAvailablePieces() to a double, then boxing back to Double. If store.getAvailablePieces() returns null, that will indeed cause a NullPointerException.

The fix is to make the third operand Double as well:

Double availablePieces = store != null ? store.getAvailablePieces()
                                       : Double.valueOf(0.0);

Now there won't be any boxing or unboxing, so it's fine for store.getAvailablePieces() to return null. You may want to then use 0.0 instead, but that's a different matter. If you're going to do that, you can change to:

Double tmp = store != null ? store.getAvailablePieces() : null:
double availablePieces = tmp == null ? 0.0 : tmp;
like image 148
Jon Skeet Avatar answered Sep 30 '22 17:09

Jon Skeet