Cazish Cazish - 3 months ago 5
Java Question

Missing a return statement somewhere?

I'm working on a basic Java assignment for school. This snippet involves searching for a specific part number in an ArrayList. When I try to compile, the IDE says I have a missing return statement. However, I can't see where it is. Do I need a return statement following the increment of the index? If so, then the return null becomes unreachable. Thank you guys very much.

public InventoryItem findInventoryItem(int searchPartNumber)
int index = 0;
boolean searching = true;
while (index < items.size() && searching){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == (searchPartNumber)){
searching = false;
return inventoryItem;

return null;



your code has several problems:

  1. after you compared first item in list and it does not match - you will stop comparing, as searching is true and you will return null
  2. in case of empty list you need to return null too

here is the fixed version:

public InventoryItem findInventoryItem(int searchPartNumber) {
    for (InventoryItem inventoryItem : items)
        if (inventoryItem.getPartNumber() == searchPartNumber)
            return inventoryItem;
    return null;