Order of execution of parameters guarantees in Java?
Asked Answered
S

1

79

Given the following function call in C:

fooFunc( barFunc(), bazFunc() );

The order of execution of barFunc and BazFunc is not specified, so barFunc() may be called before bazFunc() or bazFunc() before barFunc() in C.

Does Java specify an order of execution of function argument expressions or like C is that unspecified?

Sequestration answered 4/2, 2010 at 17:16 Comment(1)
W
90

From the Java Language Specification (on Expressions):

15.7.4 Argument Lists are Evaluated Left-to-Right

In a method or constructor invocation or class instance creation expression, argument expressions may appear within the parentheses, separated by commas. Each argument expression appears to be fully evaluated before any part of any argument expression to its right.

Wax answered 4/2, 2010 at 17:20 Comment(8)
While this is true, please please don't code in a way that makes it dependent on execution order. It's just adding complexity without adding functionality.Labyrinthodont
Indeed, "It is recommended that code not rely crucially on this specification." java.sun.com/docs/books/jls/third_edition/html/…Radu
@Labyrinthodont I disagree! if it is in the specification, then you can rely on it. For example, to read a rectangle from a file, I use this code: myRect = new Rectangle(scan.nextInt(), scan.nextInt(), scan.nextInt(), scan.nextInt()); It is concise and simple. A longer implementation would be unnecessary complexity.Romeo
I used that to avoid saving local variables in many places and made code shorter 1/2 lines for each funcion call in a parser :D. Avoiding many local variables (unless that creates more complex code) is usually good design too.Windproof
Joining this party a bit late, but I have a method to combine bytes to an int that I call like this: toInt(data[offset++], data[offset++], data[offset++], data[offset++]). I'm far too lazy to change this code, so I'm glad it will work.Raymonderaymonds
@Labyrinthodont If Java allowed temporary variable declaration prior to constructor chaining calls, I would agree with you. However, I see no viable alternative to relying on this behavior when combining constructor chaining with complex member initialization.Hirsutism
@JohnHenckel Your example is fine. But imagine if instead of Rectangle you had new MyClass(...) and after a while you decide to reorder MyClass's constructor arguments; the IDE will automatically fix the usages for you but this results in a hard to find bug since the order of the argument resolution should have been preserved. You should be careful when using this.Daniels
Came here to check because I saw this in the Eclipse compiler source: System.arraycopy(this.filenames, 0, (this.filenames = new String[length + argCount - index]), 0, length);Digestant

© 2022 - 2024 — McMap. All rights reserved.