This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'd guess that stockLevelInventory is null when you call that code. Calling a method (like toString()) on a null reference causes an NPE. Passing a null as a parameter (to product.setStockLevel()) doesn't cause an NPE, unless something in that method tries to dereference it. If you can run the code under a debugger, you can see exactly what the value of stockLevelInventory is when you reach that line of code.
In my opinion you should never let nulls live. Make sure your constructor and setXXX methods prohibit them as far as possible. Make sure all fields are initialised to a value which establishes the class invariants by the time the constructor completes.Even this cannot eliminate all nulls; for example if I were a Name object my middleName field would be null.
An alternative version of the constructor follows:-
Joined: Sep 24, 2006
Hi, Thank you both for replying. I have stepped through the debugger and stockLevelInventory is null down to the call after which if a value is not returned then should set it up for the product variable assignment, but still nulls are getting through as demonstrated with the NPE. I am not sure how this is happening.
The problem is you only assign a non-null value to stockLevelInventory deep into your nesting structure. There's a number of conditions that would mean you never got to lines 13-17, such as detailItem is null, subItems is empty, and something about a code not matching. That would mean the null you set to it at line 1, would still be there when you got to line 36. You could try setting it to 0 at line 1 (in addition to lines 14 - 17).
Joined: Oct 13, 2005
What type is it? Is it an Integer or similar? If it is, why are you using a Wrapper, rather than the primitive int?
A couple of things:
1. Arrow Anti-Pattern - the indentation and deep nesting results in an arrowhead form. Deeply nested code is more complex and is more difficult to debug. The complexity of your code is made even greater because you have nested if-statements and for-statements
2. If a method parameter should not be null, I prefer to throw an IllegalArgumentException rather than a NullPointerException. I treat NullPointerExceptions as programming errors; I just let them happen but try to find them as soon as possible through unit testing.