Lesson 1.4: Assignment Statements and Input | AP CSA

Unit 1 · Lesson 1.4 · Code Mechanics

Lesson 1.4: Assignment Statements and Input

Reading time: 8–11 min · Practice: 8 exercises · Mastery: applied scenario

What you'll learn in this lesson

  • 1.4.A. Write assignment statements correctly, explain what “initialized” means, and determine what value a variable holds after a sequence of assignments.
  • 1.4.A. Explain why null is only valid for reference types, and what happens when you use a variable before assigning it a value.
  • 1.4.B. Recognize the Scanner class as Java’s standard mechanism for keyboard input, and understand why specific input forms are outside AP exam scope.

This lesson is part of the AP CSA Course and Exam Description (effective May 2027).

AP exam weight: Assignment statement tracing appears in almost every MCQ section. Expect 2–3 questions that require you to track a variable’s value through multiple assignments, including reassignment with expressions involving the variable itself.

Key Vocabulary

Term Definition
assignment operator The = operator; evaluates the right-side expression and stores the result in the left-side variable.
initialization Assigning a value to a variable for the first time before it is used in an expression.
null A literal meaning no object is associated with this reference variable. Valid only for reference types.
NullPointerException A run-time error thrown when a method is called on a null reference.
Scanner A class in java.util used to read keyboard input; created with new Scanner(System.in).
call-by-value The mechanism Java uses to pass arguments: parameters receive copies of the argument values.
widening conversion Automatic promotion of a smaller numeric type to a larger compatible type, e.g. int to double.
narrowing conversion Converting a larger type to a smaller type; requires an explicit cast operator in Java.

The assignment operator: right side into left side

The assignment operator = does one thing: it evaluates the expression on the right side and stores the result in the variable on the left side. The direction matters. The left side is always a variable name. The right side is always an expression.

The Rule

variable = expression;

Java evaluates expression fully first, then stores the single resulting value into variable. The old value of variable is replaced.

Example: reassignment using the variable itself

int pts = 10;
pts = pts + 5;   // right side evaluates to 15, stored back into pts
pts = pts * 2;   // right side evaluates to 30, stored back into pts

After these three lines, pts holds 30. The key is that Java reads the current value of pts from memory, computes the expression, then writes the new value back. The variable on the right side refers to its value before this statement executes.

AP Trap: assignment is not equality

pts = pts + 5 is a valid Java statement. In math, it would be nonsense. In Java, read it as a command: “compute pts + 5 and store the result in pts.” Students who read = as “equals” rather than “gets” consistently mis-trace multi-step assignment sequences.

Initialization: a variable must be assigned before it is used

Declaring a variable reserves a named slot in memory. Initializing a variable means assigning it a value for the first time. In Java, you cannot use a local variable in an expression until it has been initialized. The compiler will reject the program.

The Rule

Every variable must be assigned a value before it can be used in an expression. The value must be compatible with the variable’s declared type.

Example

int count;
System.out.println(count);   // compile error: count not initialized
count = 0;
System.out.println(count);   // fine: prints 0

null: the reference type placeholder

Primitive types (int, double, boolean) must hold an actual value. Reference types (objects, Strings) can hold either a reference to an object or the special value null, which means “no object is associated with this variable.”

The Rule

null is only valid for reference types. Assigning null to a primitive type is a compile error.

String name = null;   // valid: String is a reference type
int count = null;     // compile error: int is primitive

AP Trap

A variable holding null compiles fine. The danger comes at run time: calling a method on a null reference throws a NullPointerException. You will see this pattern in later lessons when instance methods are introduced.

Expressions evaluate to a single typed value

During execution, every expression produces exactly one value, and that value has a type determined by the operands and operators involved. This is why you can chain assignment and arithmetic: int x = 3 + 4 * 2; evaluates the right side to a single int value (11) before the assignment happens.

The Rule

During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression. An int expression assigned to a double variable is automatically widened; a double expression assigned to an int variable is a compile error without an explicit cast.

AP Exclusion

Using assignment operators inside other expressions—such as a = b = 4 or arr[i += 5]—is outside the scope of the AP exam. You will never see chained assignment or assignment-inside-subscript on the test.

Scanner: reading keyboard input

The Scanner class (from java.util) reads text input from the keyboard (see the Oracle Scanner documentation). You create a Scanner object once, then call methods on it to read values:

Standard Pattern

Scanner input = new Scanner(System.in);
int age = input.nextInt();
String name = input.next();
double gpa = input.nextDouble();

AP Scope Note

The AP exam recognizes that Scanner is Java’s standard keyboard-input mechanism, but it does not test the specific method names (nextInt, next, nextDouble, etc.) in isolation. If Scanner appears on the exam, it will be as context in a larger code snippet. You will not be asked to recall the exact method names from memory.

▶ Java Code Editor
Try It Yourself
Write real Java, hit Run, and your code executes on a live compiler. Output is checked automatically.
Tier 2 · AP Practice

Practice Questions

What value is stored in val after the following code segment executes?

int val = 4;
val = val * 3;
val = val - 5;
val = val + val;
Trace each line before reading the options. Write the value of val after each statement.
A. 7
B. 14
C. 12
D. 28
B. Line 1: val = 4. Line 2: 4 * 3 = 12, so val = 12. Line 3: 12 - 5 = 7, so val = 7. Line 4: val + val = 7 + 7 = 14, so val = 14. A stops after line 3. C stops after line 2. D doubles 14 as if there were a fifth statement.
Which of the following statements will cause a compile error?

I. String label = null;
II. int count = null;
III. double ratio = null;
A. I only
B. II only
C. I and III only
D. II and III only
D. null can only be assigned to a reference type. String is a reference type, so I is valid. int and double are both primitive types, so assigning null to either is a compile error. Both II and III fail.
Consider the following code segment.

int base;
int height = 8;
int area = base * height / 2;
System.out.println(area);

Which of the following best describes what happens when this code is compiled and run?
A. A compile error occurs because base is used before it has been assigned a value.
B. The program runs and prints 0 because uninitialized int variables default to zero.
C. A run-time error occurs when line 3 executes because base has no value.
D. The program compiles but prints an unpredictable value depending on memory contents.
A. The Java compiler enforces that local variables are initialized before use. base is declared but never assigned, so the compiler rejects the program before it ever runs. B is wrong: the “default to zero” behavior applies to instance/class variables, not local variables. C is wrong: the error is caught at compile time, not run time. D is wrong: Java does not allow uninitialized local variables to produce undefined behavior.
Which of the following assignment statements will NOT cause a compile error?

I. double d = 5;
II. int n = 3.7;
III. int m = (int) 3.7;
A. I only
B. II and III only
C. I and III only
D. I, II, and III
C. Statement I: assigning int 5 to a double is a widening conversion—always allowed without a cast. Valid. Statement II: assigning double 3.7 to an int is a narrowing conversion—not allowed without an explicit cast. Compile error. Statement III: (int) 3.7 explicitly casts the double to int (result: 3), then assigns to int m. Valid. So I and III compile; II does not.
What is printed when the following code segment executes?

int p = 10;
int q = 3;
double r = p / q;
r = r + 0.5;
System.out.println(r);
Predict the value of r after line 3 before reading the options. Remember: p / q are both int.
A. 3.5
B. 3.833...
C. 4.0
D. 3.0
A. p / q is int / int = 3 (truncated). That 3 widens to 3.0 when stored in r. Then r = 3.0 + 0.5 = 3.5. B would result if division were 10.0/3. C would come from rounding 3.333 up, which Java does not do. D stops before adding 0.5.
A student writes the following code to swap the values of two variables.

int a = 5;
int b = 9;
a = b;
b = a;
System.out.println(a + " " + b);

The student expects to print 9 5 but gets a different result. Which of the following best explains why?
A. The + operator in println performs string concatenation so the output format is incorrect.
B. After a = b, both variables hold 9. Then b = a assigns 9 to b again, so both end up as 9 and the original value of a is lost.
C. Variables cannot be assigned to other variables directly; the values must be copied using a method call.
D. The assignment on line 3 fails because b has not yet been used in an expression.
B. After a = b, a holds 9 and b still holds 9. The original value of a (5) is overwritten and gone. Then b = a reads a (which is now 9) and stores 9 in b. Output is 9 9, not 9 5. The fix requires a temporary variable: int temp = a; a = b; b = temp;
Consider the following declarations.

int x = 6; double y = 2.5; boolean flag = true;

Which of the following assignment statements are valid (will NOT cause a compile error)?

I. y = x;
II. x = y;
III. flag = (x > 4);
A. I only
B. II and III only
C. I and II only
D. I and III only
D. Statement I: y = x assigns an int to a double—widening, always valid. Statement II: x = y assigns a double to an int—narrowing, compile error without cast. Statement III: (x > 4) evaluates to a boolean value (true since 6 > 4), and flag is declared boolean, so this is valid. I and III compile; II does not.
Consider the following code segment.

Scanner sc = new Scanner(System.in);
int qty = sc.nextInt();
double price = sc.nextDouble();
double total = qty * price;
System.out.println(total);

If the user types 3 then 2.5, what is printed?
Trace the values assigned to qty and price from the input, then evaluate total.
A. 5.5
B. 6
C. 7.5
D. 7
C. qty = 3 (int), price = 2.5 (double). qty * price = 3 * 2.5: one operand is double, so result is double: 7.5. A would be addition. B and D result from treating the multiplication as integer arithmetic.
PRACTICE WITH A GAME — CHOOSE ONE:

Output Predictor — Assignment Tracing

Trace the value of each variable, then type the exact output.

Question 1 of 6 Score: 0

        

Bug Hunt — Assignment Statements

Each snippet has exactly one buggy line. Click it, then submit.

Bug 1 of 7 Caught: 0

Tier 3 · AP Mastery Challenge

The Science Fair Score Tracker

A student writes a program to track a competitor's science fair score. The program reads a base score from the user, applies two adjustments, then prints the final result. A classmate runs it and gets unexpected output.

Scanner sc = new Scanner(System.in);
int score;
int bonus = 10;
score = sc.nextInt();
score = score + bonus;
bonus = bonus * 2;
score = score + bonus;
System.out.println(score);

Assume the user enters 50.

Part A: Predict the output

What does the program print when the user enters 50?
Trace each assignment in order. Write the value of score and bonus after each line before choosing.
A. 70
B. 80
C. 90
D. 60
B. After score = sc.nextInt(): score=50, bonus=10. After score = score + bonus: score=60, bonus=10. After bonus = bonus * 2: score=60, bonus=20. After score = score + bonus: score=80, bonus=20. Prints 80. A results from using bonus=10 twice. C results from using bonus=20 twice. D stops after the first addition.

Part B: Identify the uninitialized risk

If line 4 (score = sc.nextInt()) were removed, which of the following would happen?
A. A compile error would occur because score would be used on line 5 without being initialized.
B. The program would compile and run, treating score as 0 since uninitialized int variables default to zero.
C. A run-time error would occur on line 5 when Java tries to read an uninitialized variable.
D. The program would compile but the output would be unpredictable.
A. score is a local variable declared on line 2 but never initialized before line 5 uses it. The Java compiler enforces initialization of local variables before use and rejects the program at compile time. B is wrong: the zero-default rule applies to instance variables, not local variables. C is wrong: the error is caught by the compiler, not at run time. D is wrong for the same reason.

Part C: Structured response

The student wants to change the program so that bonus is doubled before the first addition to score. Rewrite lines 5–7 only (the three assignment statements after score = sc.nextInt()) so the program prints the correct new result when the user enters 50, and state what that result will be.

Extension · Beyond the Exam

Swap without a temporary variable

The classic three-line swap (temp = a; a = b; b = temp;) is the AP-expected pattern. In practice, Java also supports swapping integers using XOR arithmetic: a ^= b; b ^= a; a ^= b;. This works because XOR is its own inverse, but it is harder to read and offers no performance benefit on modern hardware. Stick with the temp variable on the AP exam.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]