AP COMPUTER SCIENCE A • USING OBJECTS AND METHODS

Assignment Statements and Input

Master how Java stores, updates, and reads data through variables, the assignment operator, and user input via Scanner.

Historical Context & Motivation

Every meaningful program must store data, transform it, and sometimes accept new data from its environment. The concept of an assignment statement—a command that binds a value to a named location in memory—is so fundamental that it predates modern programming languages entirely. Early computing pioneers recognized that without a reliable mechanism for writing to and reading from storage cells, no algorithm could progress beyond trivial computation. Understanding how assignment and input evolved provides essential context for why Java's syntax looks the way it does today.

1945
Von Neumann Architecture
John von Neumann's draft report on the EDVAC introduced the stored-program concept, where instructions and data share the same memory—making named storage locations (the precursor to variables) essential.
1957
FORTRAN and Typed Variables
IBM's FORTRAN compiler became the first widely used high-level language, introducing explicit variable declarations and the assignment statement with the '=' symbol rather than machine-code addresses.
1972
C Language and scanf
Dennis Ritchie's C language formalized standard input/output through library functions like scanf and printf, establishing the pattern of reading user input into typed variables that Java later adopted.
1995
Java 1.0 Released
Java adopted C-style assignment syntax but wrapped input in an object-oriented Scanner class (added in Java 5, 2004), reflecting the language's philosophy that everything should be an object.

This historical trajectory reveals a central question that every Java programmer must answer: How does Java let you create named containers for data, change their contents, and populate them from external sources like the keyboard? The answer lies in a precise understanding of variable declaration, the assignment operator, and the Scanner class—topics that form the backbone of virtually every AP Computer Science A exam question.

Core Principles & Definitions

Before writing any Java code, you need to internalize several foundational ideas about how the language handles data storage and modification. Java is a statically typed language, meaning every variable must declare its type before it can hold a value. An assignment statement then writes a specific value into that variable's memory location, and this value can be overwritten as many times as necessary during program execution. When the program needs data from the outside world—typically from the user's keyboard—it uses an instance of the Scanner class to read and parse that input into the appropriate type.

1

Variable Declaration

A statement like int score; reserves a named memory location of a specific type. Until assigned, a local variable holds no defined value.
2

Assignment Operator (=)

The single equals sign does not test equality—it copies the value of the right-hand expression into the variable on the left. Execution flows right to left.
3

Initialization

Combining declaration and first assignment in one line—int score = 0;—is called initialization. Java requires local variables to be initialized before use.
4

Reassignment

After initialization, you may write score = 95; to overwrite the old value. The previous value is permanently lost—Java does not keep a history.
5

Scanner Input

The Scanner class from java.util reads tokens from System.in. Methods like nextInt(), nextDouble(), and nextLine() parse user input into the correct type.
KEY TAKEAWAY
Think of a variable as a labeled box on a shelf. Declaration is placing an empty box with a specific label and size constraint (type) on the shelf. Assignment is putting an item inside that box—if an item was already there, it gets replaced. Input is like asking someone outside the room to hand you an item that you then place in the box. The box's label (variable name) never changes, but its contents can be swapped any number of times.

Visual Explanation — Memory Model of Assignment

The following diagram illustrates what happens in memory when Java executes a sequence of declaration, initialization, and reassignment statements. Each row represents the state of memory after one line of code executes. Pay special attention to how the value inside the variable's memory cell changes while its name and type remain fixed.

Each row shows the state of memory after the corresponding line executes. Notice how score = score + 10 first reads the current value of score (85), adds 10, and then overwrites score with 95. The old value is permanently replaced.

The critical insight this diagram reveals is the right-to-left evaluation order of assignment statements. Java always evaluates the entire expression on the right side of the = first, reducing it to a single value, and only then stores that result in the variable on the left. This means a statement like x = x + 1 is perfectly valid—the current value of x is read, incremented, and the new value replaces the old one. This is fundamentally different from mathematical equality, where x = x + 1 would be a contradiction.

How Assignment and Input Work in Java

Assignment Statement Syntax

DECLARATION AND INITIALIZATION
type variableName = expression;
type — a primitive type (int, double, boolean) or a reference type (String, Scanner). variableName — a valid Java identifier starting with a letter, underscore, or dollar sign. expression — any expression whose evaluated type is compatible with the declared type.
REASSIGNMENT
variableName = newExpression;
The type is NOT repeated during reassignment. The new expression must be compatible with the variable's original declared type. For primitive types, the old value is simply overwritten. For reference types like String, the variable now points to a new object.

Compound Assignment Operators

Java provides shorthand operators that combine arithmetic with assignment. The statement x += 5 is equivalent to x = x + 5. Similarly, -=, *=, /=, and %= perform subtraction, multiplication, division, and modulus before assigning the result back. The increment (++) and decrement (--) operators are special cases that add or subtract 1. While these operators are tested on the AP exam, they are merely syntactic sugar—they do not introduce new semantic concepts beyond what a standard assignment statement does.

Reading Input with Scanner

SCANNER CREATION
Scanner input = new Scanner(System.in);
This creates a Scanner object connected to the standard input stream (typically the keyboard). You must import java.util.Scanner at the top of your file. The variable input is a reference that points to the newly created Scanner object on the heap.
Common Scanner methods tested on the AP CSA exam
Scanner MethodReturn TypeDescription
nextInt()intReads the next token as an integer; throws InputMismatchException if input is not an integer.
nextDouble()doubleReads the next token as a double; accepts both integer and floating-point input.
nextLine()StringReads the remainder of the current line as a String, including spaces. Consumes the newline character.
next()StringReads a single whitespace-delimited token as a String. Does not consume the trailing newline.
Common Pitfall: nextLine() after nextInt()
When you call nextInt() followed by nextLine(), the second call consumes the leftover newline character from the integer input rather than reading a new line of text. The standard fix is to place an extra input.nextLine(); call between them to consume the dangling newline.

Type Compatibility and Implicit Casting

Java's type system governs which values can be assigned to which variables. When you assign a value of one numeric type to a variable of a wider numeric type—for instance, storing an int in a double variable—Java performs an implicit widening conversion automatically. However, the reverse—storing a double in an int—requires an explicit narrowing cast because precision may be lost. Understanding these rules is critical because the AP exam frequently tests whether a given assignment statement compiles or causes an error.

Green arrows indicate automatic (widening) conversions that Java performs implicitly. Red arrows show narrowing conversions that require an explicit cast. The dashed line between double and String indicates that no direct conversion exists—you must use String.valueOf() or string concatenation.

Notice that when an int is assigned to a double variable, the integer value gains a decimal component (e.g., 4 becomes 4.0). No information is lost. Conversely, casting a double to an int truncates the decimal portion rather than rounding it—(int) 3.99 evaluates to 3, not 4. This truncation behavior is a frequent source of exam questions. Also note the special case of string concatenation: when the + operator has a String operand, Java automatically converts the other operand to its String representation before concatenating.

Worked Example — Grade Calculator with Input

Let us trace through a complete program that declares variables, reads user input via Scanner, performs calculations with assignment statements, and outputs the result. This example demonstrates every concept covered so far in a realistic context.

Computing a Weighted Average from User Input
1
Step 1 — Import and Create ScannerAt the top of the file, write import java.util.Scanner;. Inside main, create a Scanner: Scanner in = new Scanner(System.in);. This establishes the connection to standard input. The variable in is a reference to the Scanner object.
Scanner object created and stored in variable in
2
Step 2 — Declare and Read VariablesPrompt the user and read two exam scores: System.out.print("Enter exam 1 score: "); int exam1 = in.nextInt(); // Suppose user types 88 System.out.print("Enter exam 2 score: "); int exam2 = in.nextInt(); // Suppose user types 92 Each nextInt() call blocks until the user types a value and presses Enter. The returned int is immediately stored in the declared variable.
exam1 = 88, exam2 = 92
3
Step 3 — Compute the Average (Type Consideration)We want a precise average, so we store the result in a double: double average = (exam1 + exam2) / 2.0; The right-hand side evaluates as: (88 + 92) = 180, then 180 / 2.0 = 90.0. Crucially, we write 2.0 instead of 2 to force floating-point division. If we had written (exam1 + exam2) / 2, Java would perform integer division, yielding 90 instead of 90.0—identical here, but consider inputs 87 and 92: (87 + 92)/2 = 89 (truncated), whereas (87 + 92)/2.0 = 89.5.
average = 90.0
4
Step 4 — Apply a Bonus with Compound AssignmentAdd 3 bonus points using the compound assignment operator: average += 3; This is equivalent to average = average + 3;. Java widens the int literal 3 to 3.0 before adding. The old value (90.0) is replaced by 93.0.
average = 93.0
5
Step 5 — Output the ResultSystem.out.println("Final average: " + average); The + operator concatenates the String literal with the double value, automatically converting 93.0 to "93.0". Output: Final average: 93.0
Console prints: Final average: 93.0

Common Pitfalls and Best Practices

Assignment and input are deceptively simple concepts, but the AP exam frequently exploits common misunderstandings. The table below contrasts typical mistakes with correct approaches, highlighting the underlying principle each pitfall tests.

AP-tested pitfalls with assignment and input
PitfallWhat HappensCorrect Approach
Using = to test equalityAssigns instead of comparing; may compile but produces wrong logicUse == for primitives, .equals() for objects
Integer division when decimal result expected7 / 2 yields 3, not 3.5Cast one operand: (double) 7 / 2 or use 7.0 / 2
Uninitialized local variableCompile-time error: "variable might not have been initialized"Always assign a value before using a local variable in an expression
Re-declaring a variable instead of reassigningint x = 5; int x = 10; → compile error (duplicate variable)Declare once: int x = 5; then reassign: x = 10;
nextLine() after nextInt()Reads leftover newline, returns empty stringCall an extra nextLine() to consume the newline before reading the actual line
KEY TAKEAWAY
In engineering, a register is a hardware storage location that holds a single value at a time—loading a new value destroys the old one instantly. Java variables behave identically: each assignment overwrites the previous value with no undo mechanism. When debugging, trace the value of each variable line by line, just as an electrical engineer would probe a register at each clock cycle. This disciplined tracing is the single most effective strategy for AP free-response questions.

Connection to Object References and Scope

The assignment concepts you have learned for primitive types extend directly to reference types, but with a critical distinction. When you write String a = "hello"; followed by String b = a;, the variable b does not receive a copy of the character data. Instead, it receives a copy of the reference—a pointer to the same String object in heap memory. For immutable objects like String, this distinction rarely causes bugs, but for mutable objects (like ArrayLists, which you will study later), understanding reference assignment becomes critical. Reassigning a = "world"; changes only a's reference; b still points to "hello".

Primitive assignment vs. reference assignment
ConceptThis Lesson (Primitives & Input)Advanced (Object References)
What = copiesThe actual value (e.g., 42, 3.14)The memory address (reference) of the object
Effect of reassignmentOld value is overwritten; no other variable is affectedVariable points to new object; other variables referencing the old object are unaffected
Aliasing riskNone—primitives are independent copiesTwo variables may alias the same mutable object, causing side effects
ScopeLocal variables exist only within the block {} where declaredSame scoping rules apply; object on heap may persist after reference goes out of scope (garbage collected later)

As you progress through the AP Computer Science A curriculum, you will encounter method parameters (which use assignment to copy argument values into parameter variables), instance variables (which are initialized in constructors), and array element assignment (which uses indexed notation like arr[0] = 5). All of these build directly on the assignment semantics you have mastered in this lesson.

Practice Problems

1
Consider the following code segment: int a = 5; int b = a; a = 10; What is the value of b after this code executes?
2
What is the output of the following code? int x = 10; x += 5; x *= 2; System.out.println(x);
3
Consider the following code segment: int p = 7; int q = 2; double result = p / q; System.out.println(result); What is printed?
PROBLEM 4APPLIED
Write a complete Java program that uses a Scanner to read two integer values representing the length and width of a rectangle from the user. The program should calculate and print both the area and the perimeter. Use proper variable declarations, assignment statements, and Scanner methods. Include the import statement.
PROBLEM 5CRITICAL THINKING
A student writes the following code to swap the values of two integer variables: int a = 3; int b = 7; a = b; b = a; System.out.println("a = " + a + ", b = " + b); (a) Explain what this code actually prints and why the swap fails. (b) Write a corrected version using a temporary variable. (c) Explain why a temporary variable is necessary from the perspective of how assignment overwrites values.

Summary

In this lesson you learned that a variable declaration reserves a named, typed memory location, and an assignment statement uses the = operator to store a value by evaluating the right-hand expression first and copying the result into the left-hand variable. Initialization combines these into one statement and is required for local variables before use. Compound assignment operators like += and *= provide shorthand for updating a variable based on its current value. Java's type system allows automatic widening conversions (int → double) but requires explicit casts for narrowing conversions (double → int), which truncate rather than round.

For external data, the Scanner class reads user input from System.in using methods like nextInt(), nextDouble(), and nextLine(). Key pitfalls include confusing = (assignment) with == (equality), performing integer division when a decimal result is expected, and the nextLine() newline consumption issue. These concepts form the foundation for all subsequent topics in AP Computer Science A, including method parameters, constructors, and array manipulation.

Varsity Tutors • AP Computer Science A • Assignment Statements and Input