Course contentsShow
← Java
Lesson 132 of 2,8703. Operators and ExpressionsFree lesson

Chaining Assignments and Right Associativity

Explore how assignment evaluates right-to-left, enabling chains like a = b = c = 0 and understanding evaluation order.

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:

  1. c = 5 happens first (rightmost), and c becomes 5
  2. That assignment evaluates to 5, which then gets assigned to b
  3. b = 5 evaluates to 5, which finally gets assigned to a
  4. 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.