In the statement:
fooFunc().barFunc(bazFunc());
barFunc()
can obviously not execute until both bazFunc()
and fooFunc()
have completed.
But is the order of execution of fooFunc()
and bazFunc()
guaranteed?
Related (but different!) question: Order of execution of parameters guarantees in Java?
Order of execution When you have all the three in one class, the static blocks are executed first, followed by constructors and then the instance methods.
Abstract—As the order of methods in a Java class has no effect on its semantics, an engineer can choose any order she prefers.
Java Method Overloading and parameters Parameter Order: If the two methods have the same number of parameters and the same type of parameters but if the order of parameters is different, overloading works.
The order of the parameters make a difference because it is a different signature.
The documentation for this is 15.12.4. Run-time Evaluation of Method Invocation
It says "At run-time, method invocation requires five steps. First, a target reference may be computed. Second, the argument expressions are evaluated. Third, the accessibility of the method to be invoked is checked. Fourth, the actual code for the method to be executed is located. Fifth, a new activation frame is created, synchronization is performed if necessary, and control is transferred to the method code."
In the example, fooFunc()
is called as part of computing the target reference, and bazFunc()
is one of the argument expressions, so fooFunc()
must be called first.
The JLS, Java SE 7 Edition has the following example, which says it's fooFunc()
before bazFunc()
, however I can only find the example - I haven't yet found the associated statement that specifies it:
Example 15.12.4.1-2. Evaluation Order During Method Invocation
As part of an instance method invocation (§15.12), there is an expression that denotes the object to be invoked. This expression appears to be fully evaluated before any part of any argument expression to the method invocation is evaluated. So, for example, in:
class Test2 { public static void main(String[] args) { String s = "one"; if (s.startsWith(s = "two")) System.out.println("oops"); } }
the occurrence of
s
before".startsWith"
is evaluated first, before the argument expressions = "two"
. Therefore, a reference to the string"one"
is remembered as the target reference before the local variable s is changed to refer to the string"two"
. As a result, thestartsWith
method is invoked for target object"one"
with argument"two"
, so the result of the invocation is false, as the string"one"
does not start with"two"
. It follows that the test program does not print"oops"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With