Java code inspection show a null returning method as never null

456 Views Asked by At

I found an interesting Lint inspection that I can't explain. I know Java crazy hidden stuff, so I'd like to understand what's going on here. Maybe I can impress my friends with super nerdy knowledge.

Here's a snippet of the offending code:

public void awesomeMethod()
{    
    final int[] hungryPeople = getHungryPeople();

    if ( hungryPeople != null ) // <---- Lint says that this can never be null?
    {
         solveWorldHunger( true );
         tellEveryone( false );
    }
}

Here's the related (relevant) method:

public int[] getHungryPeople()
{
   // Get hungry people data from the class's Android Intent field
   final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE );

   if ( null != values )
   {
        return Arrays.copyOf( values, values.length );
   }

   return null;
}

Is there something I'm missing here?

1

There are 1 best solutions below

0
On BEST ANSWER

You are returning null outside the method, you need to return inside getHungryPeople() in case values is null.

public int[] getHungryPeople()
{
   // Get hungry people data from the class's Android Intent field
   final int[] values = mIntent.getIntArrayExtra( HUNGRY_PEOPLE );

   if ( null != values )
   {
        return Arrays.copyOf( values, values.length );
   }

   // if values is null, return null
   return null;
}