So when you initialize your array of BigInteger
, the values are null
because you have specified an array of objects (if it was int[]
then initial values are 0).
As you can see from your constructor:
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
coef[b] = BigInteger.valueOf(a);
deg = degree();
}
You have only assigned coef[b]
, the other values remain null
.
Hence in first iteration of loop in method plus(Polynomial b)
, c.coef[0]
is null hence NullPointerException
when your loop tries to call c.coef[0].add(a.coef[0])
.
Suggestion: define a method to initialize all the BigInteger
values in an array to 0 to be consistent with declaration of int[]
and call in your constructors. Example:
private static void initializeBigIntegerArray(BigInteger[] bigIntegers) {
for (int i=0; i<bigIntegers.length; i++) {
// So you don't overwrite anything you assign explicitly
if (bigInteger[i] == null) {
bigIntegers[i] = BigInteger.ZERO;
}
}
}