Search code examples
javaoperator-precedence

Java Operator Precedence example


I know the Operator Precedence list, but I just cannot figure out what is the execution precedence in this code in "LINE 1". What Object is created before? For example: the My String or the new Precedence()? How can we apply the Operator Precedence rule in this example?

public class Precedence {
    public String s;
    public static void main (String ... args){
        String a = new Precedence().s="My String"; // LINE 1
        System.out.println(a);
    }
}

OUTPUT: My String


Solution

  • This

    String a = new Precedence().s="My String"; // LINE 1
    

    is a local variable declaration statement with an initialization expression.

    Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initializer, the initializer is evaluated and its value is assigned to the variable.

    a is the declarator. It's evaluated to produce a variable (itself). Then the initialization expression is evaluated.

    This

    new Precedence().s = "My String";
    

    is an assignment expression. The left hand side of the operator is evaluated first to produce a variable, so new Precedence() is evaluated first, instantiates the class Precedence, producing a reference to an object. Then the right hand side of the assignment is evaluated, the String literal "My String", so a reference to a String object is produced. Then the assignment happens assigning the reference to the String object to the variable s of the object referenced by the value returned by the new instance creation expression.

    Finally, since

    At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.

    The value that was assigned to the field s of the Precedence object is also assigned to the variable a.