This code throws a NullPointerException.
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
This code throws a NullPointerException.
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
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;
}
you never initialized cost, you would need to do
protected static Integer cost = 0;
becuase you cant add a number to an uninitialized object;