Chaining Assignments and Right Associativity
What You'll Learn
You'll discover how Java allows you to chain multiple assignments in a single statement and why they evaluate from right to left.
The Core Idea
In Java, you can write something like a = b = c = 0; to assign the same value to multiple variables at once. This works because the assignment operator (=) is right-associative, meaning Java evaluates the assignments from right to left, not left to right like arithmetic operators.
Think of it like a chain reaction that starts at the end: Java first assigns 0 to c, then takes that result and assigns it to b, then takes that result and assigns it to a. Each assignment operation actually returns the value that was assigned, making the next assignment possible.
How It Works
When you write:
int a, b, c;
a = b = c = 5;
Java reads this as:
a = (b = (c = 5));
Step by step:
c = 5happens first (rightmost), andcbecomes5- That assignment evaluates to
5, which then gets assigned tob b = 5evaluates to5, which finally gets assigned toa- All three variables now hold
5
Why Right-to-Left Matters
int x = 10;
int y = 20;
int z;
x = y = z = 3; // z gets 3, then y gets 3, then x gets 3
This wouldn't work if assignments evaluated left-to-right, because z wouldn't have a value yet when we tried to read it!
Key Takeaway: Assignment operators are right-associative, evaluating from right to left, which allows you to chain assignments like a = b = c = 0 to efficiently initialize multiple variables with the same value.