skip to content

Assignment & Compound Assignment

Simple assignment plus the compound forms, which quietly insert a narrowing cast — so b += 1 compiles for a byte where b = b + 1 does not. That hidden cast is exactly the detail interviewers test.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What is the simple assignment operator (=) in Java, and what does an assignment expression evaluate to?

level: juniorimportance: must knowfreq 55%

answer

  1. = stores RHS into LHS (variable/field/array element)
  2. assignment is an expression; result = the assigned value
  3. right-associative → a = b = 5 works
  4. references copy the handle, not the object
  5. = assigns, == compares

basics

~20 s

The = operator stores the value on its right into the variable on its left. An assignment is also an expression whose result is the value that was assigned, so you can write a = b = 5 and both become 5.

solid answer

~40 s

In Java, = is the simple assignment operator: it evaluates the right-hand side and stores that value (or reference) into the left-hand side, which must be a variable, field, or array element. Assignment is itself an expression that produces the assigned value, which is why chaining works: a = b = 5 first assigns 5 to b, then that result (5) to a. Assignment is right-associative and has very low precedence, so almost everything else evaluates first. For reference types, the variable holds a reference, so assignment copies the reference, not the object. A common gotcha is using = (assignment) where == (comparison) was intended; Java catches this for non-boolean types because the assignment result is not a boolean, but it compiles fine for boolean operands.

code

java · 8 lines
java
int a, b;
a = b = 5;          // chained: b=5 first, then a=5
System.out.println(a + " " + b); // 5 5

int[] x = {1, 2};
int[] y = x;        // copies the reference, not the array
y[0] = 99;
System.out.println(x[0]); // 99 — same array

go deeper

for a junior

Knows = stores the RHS into a variable and that == is different from =.

for a middle

Explains assignment is an expression, right-associative chaining, and reference vs value copy semantics.

for a senior

Articulates precedence/associativity, the boolean if (flag = true) trap, and assignability/widening rules.

for a principal

Frames lvalue/rvalue semantics, why the JLS makes assignment an expression, and how reference-copy semantics inform API contracts (defensive copying).

## What 'assignment' means A **variable** in Java is a named storage location that holds a value. The **simple assignment operator**, written `=`, puts a value into that location. The general form is: ``` leftHandSide = expression ``` The **left-hand side (LHS)** must be something that can be assigned to — called an *lvalue* in general programming terms. In Java the legal targets are: a local variable, an instance/static field, or an array element (`arr[i]`). The **right-hand side (RHS)** is any expression that produces a value. ### Step 1: how it executes 1. The RHS expression is **evaluated** to produce a value. 2. That value is **stored** into the LHS location, replacing whatever was there. ### Step 2: value types vs reference types - For a **primitive** (`int`, `double`, `boolean`, etc.) the *actual value* (e.g. the number 5) is copied into the variable. - For a **reference type** (any object, like `String` or `int[]`) the variable holds a **reference** (a handle pointing to an object on the heap). Assignment copies the *reference*, not the object. So after `b = a`, both `a` and `b` point to the *same* object; mutating through one is visible through the other. ### Step 3: assignment is an expression Unlike some languages where assignment is only a statement, in Java an assignment is also an **expression** — it has a result value. **The result of `x = expr` is the value that was assigned to `x`.** This enables two patterns: - **Chained assignment:** `a = b = 5`. Because `=` is **right-associative**, this groups as `a = (b = 5)`. First `b = 5` runs and yields `5`; that `5` is then assigned to `a`. - **Assignment inside a condition:** `while ((line = reader.readLine()) != null)` reads, stores, and tests in one expression. ### Step 4: precedence and associativity `=` has **very low precedence** — lower than arithmetic, comparison, and logical operators. So `x = a + b > c` evaluates `a + b`, then `> c`, then assigns that boolean to `x`. And it is **right-associative**, which is what makes chaining work. ### Step 5: the classic `=` vs `==` bug `=` *assigns*; `==` *compares*. Writing `if (x = y)` instead of `if (x == y)` is a famous bug. Java mostly protects you: `if (x = 5)` won't compile because the assignment yields an `int`, and `if` requires a `boolean`. But if both operands are `boolean`, `if (flag = true)` compiles and silently always assigns/uses `true` — a real trap. ### Type compatibility The RHS type must be assignable to the LHS type. Java permits **widening** automatically (`int` into a `long`, `long` into a `double`) because no information is lost, but **narrowing** (e.g. `long` into `int`) requires an explicit cast, because it can lose data.

  • Why does `a = b = 5` work, and what would `(a = b) = 5` do?
    `a = b = 5` works because `=` is right-associative and assignment is an expression returning the assigned value, so `b = 5` yields 5 which is then assigned to `a`. `(a = b) = 5` does not compile: the result of `(a = b)` is a value, not an assignable variable, so it cannot appear on the left of `=`.
  • After `String s2 = s1;`, if you do `s2 = "new"`, does `s1` change?
    No. `s2 = "new"` rebinds `s2` to a different String object; it doesn't mutate the object `s1` points to. (Strings are immutable anyway, so even mutation isn't possible.) Reassigning a reference never affects other references.

Think of a variable as a labeled box. Simple assignment is putting a new item in the box, throwing out whatever was there. For objects the box only holds a slip of paper with an address, so copying the slip lets two boxes point at the same warehouse item.

saying these in an interview costs you the question

  • Saying assignment copies the object for reference types (it copies the reference)
  • Claiming `=` and `==` are interchangeable
  • Thinking assignment is only a statement and has no value
  • Believing `(a=b)=5` is valid

context

open as a page

Explain the implicit narrowing cast performed by compound assignment, and give a case where it silently changes a value.

level: middleimportance: must knowfreq 58%

basics

~20 s

Compound assignment automatically casts the result back to the variable's type, like b += 1 meaning b = (byte)(b + 1). That hidden cast can quietly chop or wrap a value — e.g. byte b = 127; b += 1; makes b -128 with no error.

open as a page

What are compound assignment operators like += and -=, and how does `x += y` differ from `x = x + y`?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Compound operators combine an operation with assignment: x += y means roughly x = x + y. Java has +=, -=, *=, /=, %=, and the bitwise/shift ones. They are shorthand and evaluate the left side only once.

open as a page

What does it mean to assign to a final variable, and how does final interact with assigning references vs. mutating objects?

level: middleimportance: should knowfreq 30%

basics

~20 s

A final variable can be assigned only once. After that you can't reassign it. But final only locks the variable, not the object it points to — you can still change the object's contents through that reference.

open as a page

In a compound assignment to an array element or field, what is the evaluation order, and why can it matter?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Java evaluates the target's location (like the array reference and index) first and only once, then reads the old value, applies the operation with the right-hand side, and stores back. So a method used to pick the slot runs a single time.

open as a page