-3

This code throws a NullPointerException.

protected static Integer cost;
public static int incCost(int value)
{
   cost += value;
};

2 Answers2

0

Because the default value of reference types is null, not 0.

protected static Integer cost = 0; //<-- add = 0

Or, use a primitive int like

protected static int cost; //<-- defaults to 0.

You also must return an int, so you could do

public static int incCost(int value)
{
   cost += value;
   return cost;
}
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239
0

you never initialized cost, you would need to do

 protected static Integer cost = 0;

becuase you cant add a number to an uninitialized object;