zai-turner
zai-turner

Reputation: 83

What is the order of evaluation of function arguments java

So I have created a class that allows you to optionally pass in a new instance of itself:

public ExampleObject(String name, ExampleObject... exampleObjects) {

}


public static void main(String[] args) {
   ExampleFunction(new ExampleObject("Test", new ExampleObject("Test2")));
}

How would this execute? Would the constructor for the outer ExampleObject be called first, or the inner?

Upvotes: 0

Views: 1740

Answers (3)

LuCio
LuCio

Reputation: 5193

The evaluation of arguments is described by JLS 15.12.4.2.

An excerpt:

The argument expressions, if any, are evaluated in order, from left to right. If the evaluation of any argument expression completes abruptly, then no part of any argument expression to its right appears to have been evaluated, and the method invocation completes abruptly for the same reason. The result of evaluating the j'th argument expression is the j'th argument value, for 1 ≤ j ≤ n.

Applying this to your case the evaluation order is:

ExampleFunction(new ExampleObject("Test", new ExampleObject("Test2")));
- new ExampleObject("Test", new ExampleObject("Test2"))
- - "Test"
- - new ExampleObject("Test2")
- - - "Test2"

This is the order in which the arguments are called for evaluation. This means in turn that to evaluate new ExampleObject("Test", new ExampleObject("Test2")) first new ExampleObject("Test2") will be evaluated.

Upvotes: 2

NumeroUno
NumeroUno

Reputation: 1160

Since Test ExampleObject requires ExampleObject object, which here in this case Test2 ExampleObject, so Test2 ExampleObject will be created first followed by Test ExampleObject followed by ExampleFunction.
So order is from inner to outer.

Upvotes: 0

Ivan
Ivan

Reputation: 8758

Before function call all its parameters must be evaluated. So new ExampleObject("Test2") will be called first, then new ExampleObject("Test", <object created on first step>)

Upvotes: 5

Related Questions