Search code examples
javareturn

A true value is returned to the caller , even with out specifying any return value in the return statement


public class FlourPacker {
    public static boolean canPack(int bigCount, int smallCount, int goal) {
        if ((bigCount < 0 || smallCount < 0 || goal < 0))
            return false;
        if ((bigCount * 5) < goal)
            return ((goal - (bigCount * 5)) <= smallCount);
        else return ((goal % 5) <= smallCount);
    }

    public static void main(String[] args) {
        System.out.println(canPack(3, 0, 11));
    }
}

So in this problem bigCount is worth 5 and smallCount is worth 1 and I am supposed to try to get the goal number. I can not go over(the goal) with the bigCount but I can with a smallCount.

But my question is, how come in the last if and else statement I don't need to put true or false for the return? when I run it (ie. the main method that I created) it tells me true even though I never put return true in the code.


Solution

  • You don't need to specify true or false specifically. If you did, then all your if-statements would have to be if (true) or if (false).

    So, instead, you write an expression inside the if-statement that evaluates to true or false (Taking your example, if ((bigCount * 5) < goal) will be equivalent to into if (true) or if (false) after plugging in the values from the variables).

    This same idea goes for return statements (return ((goal % 5)<= smallCount) will become return true or return false).