Topic 1.4 — Assignment Statements and Input

Goal: use assignment statements to store values in variables, update variables using expressions, and understand the basics of getting input (when provided in code).

The big idea

An assignment statement uses = to store a value in a variable. The right side is an expression that is evaluated first, then the result is stored on the left.

Read: x = x + 1 as “update x to be one larger than it used to be.”

Assignment statement pattern

variable = expression;

The variable must already be declared (and for AP-style code, usually initialized).

Update a variable using its old value

This is extremely common in CSA.

int score = 10;
score = score + 5;   // now 15
score = score - 3;   // now 12

Expressions on the right side

The right side can be any valid expression.

int a = 4;
int b = 9;
int result = (a * 2) + (b / 3);

Compute the expression first, then store it.

Common mistake: confusing = and ==

  • = assigns (stores).
  • == compares (later in Unit 2).
int x = 5;   // OK
// int x == 5;  // not valid Java

Tracing assignment (AP skill)

Practice keeping track of values step-by-step.

int x = 3;
x = x + 2;
x = x * 4;
x = x - 5;

After each line, ask: “What is x now?”

Input (what matters for AP CSA)

In AP CSA, you might see code that obtains input. You should be able to read that code and determine what value ends up stored in a variable.

Your teacher may use different input methods (like a library or Scanner). The exam focuses more on understanding the effect: “a value is read and stored.”

Example: input value stored in a variable

This is the pattern you’re expected to understand:

// Pretend this function returns an int typed by the user
int n = readInt();
n = n + 1;  // update after input

Key idea: after “input,” the variable holds whatever value was provided.

Exam mindset

  • Evaluate the right side first.
  • Then store into the left variable.
  • Update-tracing is basically “memory tracking.”
  • For input, treat it as “some value is given,” then follow what the code does next.

Quick self-check

  1. What happens first in x = 2 + 3 * 4;?
  2. Trace: int x = 5; x = x - 2; x = x * 3; What is x?
  3. Why is x = x + 1 valid even though it “uses x on both sides”?
  4. If input gives n = 7, what is n after n = n / 2; (int division)?

← Back to Unit 1 topics