Search code examples
javaoperatorsorder-of-executioncompound-assignment

How is A *= B *= A *= B evaluated?


public static void main(String[] args) {
    int A=5;
    int B=2;

    A *= B*= A *= B ;

    System.out.println(A);
    System.out.println(B);
}

When I calculated this problem on paper I found A=200 B=20, but when I write it down to eclipse it shows A=100 B=20

Can you explain the solution like solving on the paper?

I tried to solve in Eclipse and by myself.

How do we solve it?


Solution

  • Starting off with A=5, B=2

    A becomes A * B * A * B, which is 100, and B becomes B * A * B, which is 20.


    In more detail:

    A *= B *= A *= B
    

    is

    A = A * (B = B * (A = A * B)) 
    

    That resolves to

    A = 5 * (B = 2 * (A = 5 * 2))
    

    which means

    A = 5 * (B = 2 * (A = 10)) // set A to 10
    A = 5 * (B = 2 * 10)
    A = 5 * (B = 20) // set B to 20
    A = 5 * 20
    A = 100 // set A to 100