Home > Software engineering >  What is the order of execution of method calls in a statement
What is the order of execution of method calls in a statement

Time:07-14

Just something I've been wondering about, and I wanted to understand how the compiler achieves this task.

class HelloWorld {
    public static void main(String[] args) {
        double d = Double.valueOf(sum(1, plusOne(2)));
    }
    
   static int sum(int a, int b) {
       return a b;
   }
   
   static int plusOne(int a) {
       return   a;
   }
}

Draw your attention to the 3rd line:

double d = Double.valueOf(sum(1, plusOne(2)));

My question here is how is this statement executed? Since I'm pretty sure this qualifies as an expression, it should be evaluated left to right I belive.

So my assumption would be that the Double.valueOf() is called first. However, now I'm passing in the method call sum() as the argument to the valueOf() method, and it's output will serve as the input to valueOf().

As this is happening would we assume that the execution of valueOf() is paused as the sum() method is evaluated? Similarly when sum() is executed and plusOne() is used as the second argument of sum(), is it also paused as plusOne() is evaluated?

I hope my question makes sense. It's just basically what is the order of evaluation here, and what is happening in-between? Are the execution of methods being "paused" whilst an argument for a method is being evaluated? Or is something different going on? Perhaps even the inner statements are being evaluated first? Is plusOne() evaluated first, then sum() then valueOf()? I doubt it but I'm here trying to find out

Any help to answer this question any links to some further reading material would be very appreciated.

CodePudding user response:

In order to be able to invoke Double.valueOf, we need the value of its argument, i.e. sum(1, plusOne(2)). So we try to invoke sum. But we need the arguments, i.e. 1 (no problem there) and plusOne(2).

So what is actually invoked first is plusOne(2), with result 3, then we invoke sum(1, 3) with result 4, and finally Double.valueOf(4).

So while expressions in general are evaluated left-to-right, arguments to any single expression need to be evaluated before the expression itself can be evaluated. So it would be more complete to call it "left-to-right-innermost-to-outermost" evaluation order.

As a more complete example:

foo(bar()) baz(boo())

The execution order would be:

  1. bar -- left innermost
  2. foo -- left outermost
  3. boo -- right innermost
  4. baz -- right outermost

CodePudding user response:

Like in maths:

  1. plusOne(2) => 3
  2. sum(1, 3) => 4
  3. Double.valueOf(4) => 4.0
  4. double d = 4.0
  •  Tags:  
  • java
  • Related