APCSA 1.4 — Assignment Statements and Input

How Java stores, updates, and receives information during a program’s execution.

1) Assignment Statements

An assignment statement stores a value into a variable using the assignment operator =. It means “evaluate the expression on the right, then store the result into the variable on the left.”

Example

int score = 10;       // declare and initialize
score = score + 5;    // update: score becomes 15
Rules & Pitfalls:
• The variable on the left must already exist and have a compatible type.
= is assignment; == is comparison.
• You cannot assign to a literal (e.g., 5 = score; is invalid).

Right-to-Left Evaluation

Java evaluates the right-hand side first, then assigns the result:

x = y + 3;   // 1) read y  2) compute y + 3  3) store into x

2) Getting Input with Scanner

In APCSA, user input commonly uses the Scanner class from java.util. Create a scanner that reads from the keyboard (standard input).

import java.util.Scanner;

public class InputDemo {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter your age: ");
    int age = input.nextInt();     // assignment from input

    System.out.print("Enter your name: ");
    String name = input.next();    // reads a single word

    System.out.println("Hello, " + name + ". You are " + age + " years old.");

    input.close();
  }
}

Common Scanner Methods

Method Purpose Example Input
nextInt() Read an integer. 17
nextDouble() Read a decimal (double). 3.14
next() Read one word (stops at space). Cusack
nextLine() Read an entire line (can include spaces). Joe Cusack
Tip: After using nextInt() or nextDouble(), call input.nextLine() once to consume the leftover newline before using nextLine() for text.

3) Assignment + Input Together

Assignments often store values directly from user input and then use those values in expressions.

import java.util.Scanner;

public class DoubleNumber {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int num = input.nextInt();  // assignment from input

    int doubleNum = num * 2;    // computed assignment
    System.out.println("Twice your number is " + doubleNum);

    input.close();
  }
}

4) APCSA Relevance

College Board AP CSA Unit 1 (Primitive Types) expects you to declare variables, assign and reassign values, read input, and print results. Mastering assignment and input prepares you for later units on expressions, methods, and objects—nearly all data handling begins here.

Variables Assignment Input/Output Scanner Primitive Types