Loading
Master how Java stores, updates, and reads data through variables, the assignment operator, and user input via Scanner.
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.
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.
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.
int score; reserves a named memory location of a specific type. Until assigned, a local variable holds no defined value.int score = 0;—is called initialization. Java requires local variables to be initialized before use.score = 95; to overwrite the old value. The previous value is permanently lost—Java does not keep a history.Scanner class from java.util reads tokens from System.in. Methods like nextInt(), nextDouble(), and nextLine() parse user input into the correct type.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.
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.
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.
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.| Scanner Method | Return Type | Description |
|---|---|---|
nextInt() | int | Reads the next token as an integer; throws InputMismatchException if input is not an integer. |
nextDouble() | double | Reads the next token as a double; accepts both integer and floating-point input. |
nextLine() | String | Reads the remainder of the current line as a String, including spaces. Consumes the newline character. |
next() | String | Reads a single whitespace-delimited token as a String. Does not consume the trailing newline. |
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.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.
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.
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.
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.inSystem.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.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 += 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.System.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.0Assignment 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.
| Pitfall | What Happens | Correct Approach |
|---|---|---|
Using = to test equality | Assigns instead of comparing; may compile but produces wrong logic | Use == for primitives, .equals() for objects |
| Integer division when decimal result expected | 7 / 2 yields 3, not 3.5 | Cast one operand: (double) 7 / 2 or use 7.0 / 2 |
| Uninitialized local variable | Compile-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 reassigning | int 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 string | Call an extra nextLine() to consume the newline before reading the actual line |
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".
| Concept | This Lesson (Primitives & Input) | Advanced (Object References) |
|---|---|---|
| What = copies | The actual value (e.g., 42, 3.14) | The memory address (reference) of the object |
| Effect of reassignment | Old value is overwritten; no other variable is affected | Variable points to new object; other variables referencing the old object are unaffected |
| Aliasing risk | None—primitives are independent copies | Two variables may alias the same mutable object, causing side effects |
| Scope | Local variables exist only within the block {} where declared | Same 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.
int a = 5;
int b = a;
a = 10;
What is the value of b after this code executes?int x = 10;
x += 5;
x *= 2;
System.out.println(x);int p = 7;
int q = 2;
double result = p / q;
System.out.println(result);
What is printed?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.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.
Keep learning with more lessons from the same subject.