PumpkinBreath
PumpkinBreath

Reputation: 915

Is it possible for a method that returns a primitive type to return null?

I am practicing with ArrayList and have come up against something I don't understand. I have a class Knapsack and a class Item, I am filling up the knapsacks with items and performing various tests on the knapsacks etc.

One of the public Knapsack methods returns the total weight of the non-null items in the knapsack. Another Knapsack method which is a static class method returns the heaviest knapsack in an array of Knapsack objects.

When I call this code to test if the Items in the knapsack are equal to 1000g:

testIntEqual("heaviestKnapsack", 1000, Knapsack.heaviestKnapsack(sacks).totalWeightInGrammes());

IntelliJ gives me a NullPointerException warning for the call totalWeightInGrammes()

Here are the implementations of the heaviestKnapsack() and totalWeightInGrammes() methods:

public static Knapsack heaviestKnapsack(Knapsack[] knapsacks) {
    // TO DO
    if (knapsacks.length != 0) {
        Knapsack heaviest;
        int index = 0;
        while (true) {
            heaviest = knapsacks[index];
            if (heaviest == null) {
                index++;
            } else {
                break;
            }
        }
        for (Knapsack knapsack : knapsacks) {
            if (knapsack != null && (getTotalKnapsackWeight(knapsack) > getTotalKnapsackWeight(heaviest))) {
                heaviest = knapsack;
            }
        }
        return heaviest;
    }
    return null;
}

public int totalWeightInGrammes() {
    // TO DO
    if (!knapsackItems.isEmpty()) {
        int totalWeight = 0;
        for (Item i : knapsackItems) {
            if (i != null) {
                totalWeight += i.getWeightInGrammes();
            }
        }
        return totalWeight;
    }
    return 0;
}

I am really confused as to why IntelliJ is warning me about NPE when I have tested thoroughly for null in these methods and totalWeightInGrammes() returns the primitive type int.

Many thanks for all comments :)

Upvotes: 2

Views: 198

Answers (1)

azro
azro

Reputation: 54148

Knapsack.heaviestKnapsack(sacks).totalWeightInGrammes()
         ^^^^                    ^^^^ 
     can return null          NPE warning

You have a NPE warning on .totalWeightInGrammes() because heaviestKnapsack() can return null, so it will be the call to .totalWeightInGrammes() that will throw the NPE

Upvotes: 3

Related Questions