NullPointerException when adding to BigDecimal
- by Dan
String[] toppings = new String[10];
BigDecimal toppingsPrice = null;
toppings[0] = req.getParameter("extraCheese");
toppings[1] = req.getParameter("moreTomatoes");
toppings[2] = req.getParameter("extraOnions");
// ...
for(int i = 0; i < toppings.length; i++) {
if(toppings[i] != null) {
toppingsPrice.add(new BigDecimal("0.99")); // <-- NPE is caused here.
toppingsPrice = toppingsPrice.setScale(2, BigDecimal.ROUND_HALF_EVEN);
}
}
I am getting a NullPointerException in the above code when adding 0.99 to toppingsPrice. I am working with money values, so I have used BigDecimal. Is there something wrong with how I am adding the 0.99c price?