-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
  • 198,278
  • 20
  • 158
  • 249
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;

IDKWhatImDoing
  • 137
  • 1
  • 13