collint25
collint25

Reputation: 311

Are these two equivalent?

Do both of these have the same result? If so I'm just confused on why you don't have to have an else statement returning inventoryList.size(); on the first piece of code because if the if statement is true won't it return 0 and inventoryList.size();?

public int numItems() {
    if (inventoryList.isEmpty()) {
        return 0;
    }
    return inventoryList.size();
}

And

public int numItems()   {
  if (inventoryList.size() != 0)  {
     return inventoryList.size();
  }
  else  {
     return 0;
  }
}

Upvotes: 0

Views: 46

Answers (4)

Maxqueue
Maxqueue

Reputation: 2444

No the return statement exits out of the function. Think of it like a go to statement which is what is happening behind the scenes.

Upvotes: 0

TomDillinger
TomDillinger

Reputation: 194

When a return statement is executed, that method stops there and no more code is executed. Therefore these two functions are equal.

Upvotes: 0

Jon Kiparsky
Jon Kiparsky

Reputation: 7743

They are equivalent. In either case you can skip the else, since you return from the consequent of your if statement.

Upvotes: 0

AlanObject
AlanObject

Reputation: 9943

Is there some reason you are trying to wrap the inventoryList.size() method? You should just go

public int numItems() { return inventoryList.size(); }

What doesn't that do that you want to do?

Upvotes: 1

Related Questions