Lesson 1.4 · Unit 1 · CED topic 1.4

Assignment statements and input

Declaring a variable creates a box. An assignment statement puts something in it. This is where programs start to move: values are computed, stored, and changed as the statements run, and the skill the exam tests most here is tracing, meaning following those changes line by line and keeping track of what each variable holds.

Required content · LO 1.4.A, LO 1.4.B

Learning objectives.

  • 1.4.A. Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.
  • 1.4.B. Develop code to read input.

Essential knowledge.

  • 1.4.A.1. Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or null if there is no object. The literal null is a special value used to indicate that a reference is not associated with any object.
  • 1.4.A.2. The assignment operator = allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.
    Outside the course: The use of assignment operators inside expressions (e.g., a = b = 4; or a[i += 5]) is outside the scope of the AP Computer Science A course and exam.
  • 1.4.A.3. 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.
  • 1.4.B.1. Input can come in a variety of forms, such as tactile, audio, visual, or text. The Scanner class is one way to obtain text input from the keyboard.
    Outside the course: Any specific form of input from the user is outside the scope of the AP Computer Science A course and exam.

The assignment operator

The assignment operator = stores a value in a variable. It does not mean "equals" the way it does in algebra. It means: evaluate the expression on the right, then store the result in the variable on the left.

int score = 10;          // initialization: the first time score gets a value
score = score + 5;       // evaluate score + 5 (that is 15), then store it in score

Because the right side is evaluated first, a statement like score = score + 5 is perfectly sensible: it reads the old value, adds, and stores the new one. Rules that follow from this:

  • A variable must be assigned a value before it is used in an expression. A variable is initialized the first time it is assigned a value.
  • The value must come from a compatible data type. An int can go in a double; a double cannot go in an int without a cast (Lesson 1.5).
  • A variable of a reference type can be assigned a new object, or the special literal null, which means the variable is not associated with any object.
  • During execution an expression is evaluated to produce a single value, and that value has a type determined by the expression.

Assignment is a statement, not something to use inside another expression: forms such as a = b = 4; are outside the course.

Tracing

A trace table is a table with one column per variable and one row per statement. Fill in each row with the values after that statement runs. Tracing on paper is the best habit you can build for this course, because it is how you find out what code really does.

Worked example · a trace

Trace this code and give the final values.

int a = 5;
int b = a;
a = a + 2;
b = b * 3;
System.out.println(a + " " + b);
After the statementab
int a = 5;5not yet declared
int b = a;55
a = a + 2;75
b = b * 3;715
7 15

The line int b = a; copies the value of a at that moment. Later changing a does not change b, because the two variables are separate boxes.

Worked example · swapping two values

Swap the values of x and y. Without a helper variable the first assignment would destroy a value, so a third variable holds it temporarily.

int x = 3;
int y = 8;
int temp = x;
x = y;
y = temp;
System.out.println("x = " + x + ", y = " + y);
After the statementxytemp
start38
int temp = x;383
x = y;883
y = temp;833
x = 8, y = 3

Try it without temp: x = y; would make both variables 8, and the original 3 would be gone with no way to recover it.

Worked example · what the compiler refuses

A variable must be assigned a value before it is used.

public class Main {
    public static void main(String[] args) {
        int total;
        int doubled = total * 2;
    }
}
Main.java:4: error: variable total might not have been initialized
        int doubled = total * 2;
                      ^
1 error

The declaration made the box but never put anything in it, so reading it makes no sense and the compiler refuses. Assigning an incompatible value is also refused: int n = "five"; fails with incompatible types: String cannot be converted to int.

Getting data in: input

Programs also take input, which can be tactile, audio, visual, or text. The Scanner class is one way to obtain text typed at a keyboard, and the only form of input this course uses in code is reading from a file (Lesson 4.6). Keyboard input appears in many classroom programs, so the idiom is worth recognizing, but no specific form of keyboard input is tested on the exam.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Your age: ");
        int age = in.nextInt();
        System.out.println("Next year you will be " + (age + 1));
    }
}

The call in.nextInt() waits for the user, reads an int, and the = stores it in age. Everything after that is ordinary assignment and expressions.

Exam focus

Tracing questions dominate this topic: a short segment of assignments, then "what is the value of b after the code runs?" Build a trace table every time; do not do it in your head. Expect x = x + 1 style statements, copies such as b = a followed by a change to a, and swaps. Remember that the right side is evaluated first, and that the type of the whole expression, not of the variable on the left, controls integer or real division.

Practice
  1. What are the values of a and b after the code runs?
    int a = 4;
    int b = 9;
    a = b;
    b = a + 1;
    System.out.println(a + " " + b);
    Show answer

    a is 9 and b is 10. After a = b; both variables hold 9. Then b = a + 1; stores 10 in b, and a is untouched.

  2. What is printed?
    int n = 6;
    n = n * 2;
    n = n - 5;
    System.out.println(n);
    Show answer

    7. The value goes 6, then 12, then 7.

  3. Which statement correctly increases count by 3?
    A.  count + 3 = count;
    B.  count = count + 3;
    C.  3 + count;
    D.  count == count + 3;
    Show answer

    B. The assignment operator needs a variable on the left and an expression on the right. A reverses the sides, C computes a value and throws it away, and D is a comparison, not a change.

  4. Does this compile? Why or why not?
    int price;
    System.out.println(price);
    Show answer

    No. price is declared but never assigned a value before it is used, so the compiler reports that it might not have been initialized.

  5. Trace the code and give the final output.
    int p = 2;
    int q = 3;
    p = p + q;
    q = p - q;
    p = p - q;
    System.out.println(p + " " + q);
    Show answer

    3 2. After the first assignment p is 5. Then q = 5 - 3 is 2, and p = 5 - 2 is 3. This sequence swaps the two values with no helper variable, but only because the values are numbers.

  6. A variable String title has been declared and not assigned. Which statement is valid, and what does it do?
    A.  title = null;
    B.  title = 5;
    C.  title = "";
    Show answer

    A and C are both valid. null means the variable refers to no object, and "" is a real String object with no characters. B is invalid because an int is not a String.

← 1.3 Expressions and output1.5 Casting and the range of variables →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course