Odd NullPointerException

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:

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

If the storage is not null and store.getAvailablePieces () is null. I do not understand why I am getting an exception here.

Any ideas?

+6
source share
1 answer

I am 99% sure that this is due to the behavior of the conditional statement. I believe your code is equivalent:

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

In other words, it decompresses the result of store.getAvailablePieces() to double , and then returns to double . If store.getAvailablePieces() returns null , this will indeed throw a NullPointerException .

The fix is ​​to make the third operand double :

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

Now there will be no boxing or unboxing, so it is normal for store.getAvailablePieces() to return null . You can use 0.0 instead, but that is another matter. If you are going to do this, you can change to:

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

All Articles