Unit 1 · 15 min

1.4 Assignment Statements and Input

= means "store the value on the right in the variable on the left", not "is equal to".

Summary, objectives and course and exam description (CED) codes

The assignment operator = evaluates the expression on the right and stores the value in the variable on the left. Every variable must be assigned a value of a compatible type before it is used, and a reference variable can hold a new object or null. Input can come in many forms; the Scanner class is one way to read text from the keyboard.

By the end of this session you can

  • 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.

1.4.A1.4.A.11.4.A.21.4.A.31.4.B1.4.B.1

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. Giving a variable its first value

Every variable must be assigned a value before it can be used in an expression, and that value must be of a compatible data type. A variable is initialized the first time it is assigned a value 1.4.A.1.

// does not compile
int n;
System.out.println(n);

Real view: the compiler rejects the code because n has no value yet.

error: variable n might not have been initialized

Declaring and initializing can happen in one statement or in two:

int lives = 3;     // declared and initialized together
int bonus;         // declared only
bonus = 2;         // initialized here
System.out.println(lives + bonus);

Output:

5

A reference variable can be assigned a new object, or null if there is no object. The literal null is a special value that means a reference is not associated with any object 1.4.A.1.

String title = "Chess Club";
String nickname = null;      // no String object yet
System.out.println(title);
System.out.println(nickname);

Output:

Chess Club
null

Printing a null variable prints the word null. Calling a method on it is different: that throws a NullPointerException (topic 1.14).

2. The assignment operator

The assignment operator = gives a variable its first value (initializes it) or replaces the value it holds. Java stores the value of the expression on the right side in the variable on the left side 1.4.A.2.

Java evaluates the right side first, using the current values, and then stores the result. So c = c + 1; is not an equation: it adds 1 to c.

int c = 4;
c = c + 1;
System.out.println(c);

Output:

5

Assigning a primitive copies the value. After int b = a;, changing a does not change b.

int a = 10;
int b = a;   // b gets a copy of 10
a = 99;
System.out.println(a + " " + b);

Output:

99 10

For a reference variable, the value copied is the reference, so both variables then refer to the same object (see aliasing in topic 1.14).

Outside the course: assignments inside expressions, such as a = b = 4;.

3. Expressions produce one value

During execution, an expression is evaluated to produce a single value, and that value has a type based on the evaluation 1.4.A.3. a + 4 is an expression: it produces a value. A simple statement, such as an assignment or a method call, is a complete instruction that ends in ;, such as int b = a + 4;.

int a = 7;
double half = a / 2.0;  // the expression a / 2.0 has type double
int whole = a / 2;      // the expression a / 2 has type int
System.out.println(half + " " + whole);

Output:

3.5 3

The type of the expression must be compatible with the variable. a / 2.0 is a double, so it could not be stored in an int variable without a cast (topic 1.5).

4. Trace tables

A trace table follows the values step by step. Each row runs one line of code and shows the values stored afterwards. A blank cell means the variable does not exist yet.

int a = 3;
int b = a + 4;
a = b * 2;
b = b - a;
System.out.println(a + " " + b);
Line Code a b
1 int a = 3; 3
2 int b = a + 4; 3 7
3 a = b * 2; 14 7
4 b = b - a; 14 -7

Output:

14 -7

Watch out: line 4 uses the NEW value of a (14, not 3). Update your trace table after every line; never use a value from memory.

5. Input

Input can come in a variety of forms, such as tactile (touch), audio, visual or text. The Scanner class is one way to get text input from the keyboard 1.4.B.1. No specific form of user input is tested on the AP® exam, so you only need the idea.

import java.util.Scanner;

public class Greeting
{
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Name?");
        String name = input.nextLine();
        System.out.println("Age?");
        int age = input.nextInt();
        System.out.println("Hi " + name + ", next year you will be " + (age + 1));
    }
}

Real view: the console when the user types Ana and 16 (the typed lines are the user’s input).

Name?
Ana
Age?
16
Hi Ana, next year you will be 17

Lock it in: memory hooks

  • Assignment directionRight side first, then store left: the value flows from right to left.
  • Trace tablesOne line, one row: update the table after every line, never from memory.

Common misconceptions

  • "= means "is equal to", like in math."

    Not quite. In Java, = means "store the value on the right in the variable on the left". So c = c + 1; is not an impossible equation: it adds 1 to c.

  • "After int b = a; changing a also changes b."

    Not quite. Assigning a primitive copies the value. b keeps its own copy, so a later change to a does not affect b.

  • "A declared variable starts at 0, so it can be printed right away."

    Not quite. A local variable must be assigned a value before it is used. int n; followed by System.out.println(n); does not compile.

Exam traps

  • In a trace, each line uses the NEW values from the lines before it. Update your trace table after every line; never use a value from memory.
  • Using a variable before it has a value does not compile.
  • Assigning a primitive copies the value; assigning a reference copies the reference, so both variables refer to the same object.

2PracticeRecall it, then check yourself

In 30 seconds

  1. A variable must be assigned a value of a compatible type before it is used; the first assignment initializes it.
  2. A reference variable can be assigned a new object, or null when there is no object.
  3. = evaluates the right side using current values, then stores the result in the variable on the left.
  4. An expression is evaluated to one value, and that value has a type.
  5. Input can be tactile, audio, visual or text; the Scanner class is one way to read keyboard text.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 4 questions

Checkpoint: Assignment Statements and Input

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 What is printed? 1.4.A.2, 1.4.A.3
    int x = 4;
    int y = x * 2;
    x = y - x;
    y = x + y;
    System.out.println(x + " " + y);
    Show answer

    Answer: D. x 4, y 8; x = 8 - 4 = 4; y = 4 + 8 = 12. A forgets the last line. B takes x as 8 (the value of y) instead of 8 - 4. C adds y to itself (8 + 8) instead of using x.

  2. 2 Which statement best describes the Scanner class? 1.4.B.1
    Show answer

    Answer: B. Scanner is one way to read keyboard text; input can come in many forms (tactile, audio, visual or text). A describes output, done by System.out. C and D are wrong because Scanner is only one of many ways to get input.

  3. 3 The following code segment is intended to print 100, but it does not compile. Which of the following best explains why? 1.4.A.1
    int steps;
    steps = steps + 100;
    System.out.println(steps);
    Show answer

    Answer: A. Every variable must be assigned a value before it is used in an expression. steps is declared but not initialized, so steps + 100 does not compile. B is wrong because 100 is far inside the int range. C is wrong because variables can be assigned many times. D is wrong because an int can be added to an int.

  4. 4 Consider the following code segment. What is printed? 1.4.A.2, 1.4.A.3
    int a = 6;
    int b = a;
    a = a * 3;
    b = b + a;
    System.out.println(a + " " + b);
    Show answer

    Answer: C. b = a copies the value 6, so b is 6. Then a becomes 18 and b becomes 6 + 18 = 24. A treats b as linked to a. B adds the new a to itself, as if b were 18. D adds the old value of a (6) instead of the current value 18.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Forms of input named in the course four forms CED 1.4.B.1
    1. tactile
    2. audio
    3. visual
    4. text

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Assignment statementtap to flip

    A statement that uses = to store the value of the expression on the right in the variable on the left.

    Example and CED codes
  • Initializationtap to flip

    Giving a variable its first value. A variable must be initialized before it is used in an expression.

    Example and CED codes
  • Expressiontap to flip

    Code that is evaluated to a single value with a type. An arithmetic expression combines numeric values, variables and operators.

    Example and CED codes
  • Variabletap to flip

    A named storage location that holds a value, which can change while the program runs. Every variable has a name and a data type.

    Example and CED codes
  • nulltap to flip

    A special literal meaning a reference variable is not associated with any object.

    Example and CED codes
  • Literaltap to flip

    The code representation of a fixed value, such as 42, 3.5, true or "hi".

    Example and CED codes
  • Scanner (file input)tap to flip

    The java.util class that reads data from a file: Scanner(File f) with nextInt, nextDouble, nextBoolean, next, nextLine, hasNext and close.

    Example and CED codes

Questions students ask

What does = mean in Java?

= is the assignment operator. Java evaluates the expression on the right, then stores that value in the variable on the left. It does not test whether two values are equal.

What does it mean to initialize a variable?

A variable is initialized the first time it is assigned a value, as in int lives = 3; or lives = 3; after int lives;. A variable must be initialized before it is used in an expression.

What is null in Java?

null is a special literal that means a reference variable is not associated with any object. Plant r = null; declares a variable that can refer to a Plant but refers to none yet.

Is Scanner tested on the AP® Computer Science A exam?

No specific form of user input is tested. You only need to know that input can come in many forms and that the Scanner class is one way to get text input from the keyboard.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure