2

Inspired by another question, I started wondering about the well-definedness of the following Java code:

public class Test {
    List<Object> foo;

    Object bar() {
        foo = new ArrayList<Object>():
        return(/* Anything */);
    }

    void frob() {
        foo.add(bar());
    }
}

In this case, does the Java specification specify a strict order of evaluation for the dot operator in frob? Is left-to-right evaluation guaranteed such that the add method is always executed on the list that was there before bar replaces the field with a new list, or can there legally be compilers that let bar execute before the foo field is fetched in frob, thus executing the add method on the new list?

I suspect that left-to-right evaluation is guaranteed, but is there wording in the specification to this effect?

Community
  • 1
  • 1
Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • C and C++ alow somthings to be implementation defined or not well defined so implementations can use the most efficient for their environment. They sacrifice portability for performance. Java has the opposite design choice. – Raedwald Aug 30 '14 at 19:39

1 Answers1

1

Yes, this is part of Run-time Evaluation of Method Invocation - Compute Target Reference

If the form is Primary . [TypeArguments] Identifier involved, then:

  • If the invocation mode is static, then there is no target reference. The Primary expression is evaluated, but the result is then discarded.

  • Otherwise, the Primary expression is evaluated and the result is used as the target reference.

Then comes the evaluation of method arguments.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724