Search code examples
javaoperator-precedence

Java Order of Operation


I am having some problems understanding stacks and order of operations in java. If I had the following:

operation(7, 2)

public int operation(int x, int y) {
    if (x == y)
        return 0;
    else
        return operation(x – 1, y) + 2;
}

What would be the result? I am being told that it should be a single number result but I don't understand how (x – 1, y) + 2 can be single number. I have gotten it to:

(x – 1, y) + 2
(7 - 2, 2) + 2
(5, 2) + 2

But I don't understand the method for adding the 2 at the end. Wouldn't this need to return both values separated by a comma?


Solution

  • Wouldn't this need to return both values separated by a comma?

    Nope.

    operation(x – 1, y) + 2 is a recursive function.

    operation(7 - 1, 2) + 2 => operation(6, 2) + 2 This calls the operation function with arguments 6 and 2 (similar to how you did the initial call). This call will eventually end up with a number to which 2 is added and returned.

    Taking a smaller number for better visualization operation(4, 2)

    operation(4, 2) -> return operation(3, 2) + 2
    operation(3, 2) -> return operation(2, 2) + 2
    operation(2, 2) -> return 0 (the base case)
    .. stack unwinds
    operation(3, 2) -> return 0 + 2
    operation(4, 2) -> return 2 + 2