1.4 - Assignment Stataments and Input

superdancer16

Introduction

Now that you understand variables and expressions, you need to know how to store values in variables and get information from users. Topic 1.4 introduces the assignment operator, which allows you to initialize and change variable values, and briefly covers reading input using the Scanner class.

The assignment operator is one of the most frequently used operators in programming. Understanding how assignment works, especially with expressions, is essential for manipulating data effectively in your programs.

The Assignment Operator

What is Assignment?

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.

Basic syntax:

variable = expression;

The right side is evaluated first, then the result is stored in the variable on the left.

Simple examples:

int x = 5;              // Assign 5 to x
double price = 19.99;   // Assign 19.99 to price
boolean flag = true;    // Assign true to flag

Initialization vs. Reassignment

Initialization is the first time a variable is assigned a value:

int score;              // Declaration (no value yet)
score = 100;            // Initialization (first value assigned)

You can also declare and initialize in one statement:

int score = 100;        // Declaration and initialization combined

Reassignment is changing the value after initialization:

int count = 10;         // Initialization
count = 20;             // Reassignment (new value)
count = 30;             // Reassignment again

Important rule: Every variable must be assigned a value before it can be used in an expression.

// WRONG
int x;
int y = x + 5;          // Error! x has no value yet

// CORRECT
int x = 10;
int y = x + 5;          // Now x has a value

Assignment with Expressions

The right side of an assignment can be any expression that evaluates to a compatible type:

int a = 5;
int b = 3;
int sum = a + b;            // sum gets 8
int product = a * b;        // product gets 15
int result = (a + b) * 2;   // result gets 16

The expression is evaluated first, then the result is stored:

int x = 10;
int y = x + 5;              // Right side: 10 + 5 = 15
                            // y gets 15

Using the same variable on both sides:

int count = 10;
count = count + 5;          // Right side: 10 + 5 = 15
                            // count now stores 15

This is valid because the right side is evaluated first (using the old value of count), then the result is stored back into count.

Assignment Flow

Step-by-step evaluation:

int a = 5;
int b = 3;
int c = a + b * 2;
  1. Evaluate right side:
  2. Multiply first:
  3. Add:
  4. Store in c:

More complex example:

int x = 10;
int y = 5;
x = x + y;              // Step 1: Evaluate x + y = 10 + 5 = 15
                        // Step 2: Store 15 in x
y = x - y;              // Step 1: Evaluate x - y = 15 - 5 = 10
                        // Step 2: Store 10 in y

After execution:

Type Compatibility

The value being assigned must be compatible with the variable's data type:

// CORRECT - compatible types
int x = 5;
double y = 3.14;
boolean flag = true;

// CORRECT - int can be assigned to double (widening)
double z = 10;          // 10 becomes 10.0

// WRONG - incompatible types
int a = 3.14;           // Cannot store double in int
boolean b = 1;          // Cannot store int in boolean
int c = "hello";        // Cannot store String in int

Reference Types and null

For reference types (like String, ArrayList, or custom objects), variables 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.

String name = "Alice";      // name refers to "Alice"
name = null;                // name now refers to nothing

String text = null;         // text initialized to null
if (text != null) 
{
    System.out.println(text.length());  // Safe check
}

Attempting to use a null reference causes a NullPointerException:

String s = null;
int len = s.length();       // NullPointerException!

Reading Input

The Scanner Class

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.

Note: The AP exam does not test specific forms of input. You may see Scanner in code, but you won't need to write Scanner code from scratch on the exam.

Basic Scanner Usage

To read input, you need to:

  1. Import the Scanner class
  2. Create a Scanner object
  3. Call Scanner methods to read data
import java.util.Scanner;

public class InputExample 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter your age: ");
        int age = input.nextInt();
        
        System.out.print("Enter your GPA: ");
        double gpa = input.nextDouble();
        
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
    }
}

Common Scanner Methods

While specifics are outside the exam scope, here are basic methods:

Important: For the AP exam, you only need to understand what Scanner does conceptually. You will not be asked to debug Scanner code or write Scanner programs.

Common Mistakes

Mistake 1: Using uninitialized variables

// WRONG
int x;
System.out.println(x);      // Error! x has no value

// CORRECT
int x = 0;
System.out.println(x);      // Prints 0

Mistake 2: Confusing = with ==

int x = 5;

// WRONG - This is assignment, not comparison
if (x = 10) {               // Syntax error
    System.out.println("Equal");
}

// CORRECT - Use == for comparison (covered in Unit 3)
if (x == 10) {
    System.out.println("Equal");
}

Mistake 3: Misunderstanding order of evaluation

x = x * 2;                  // Right side first: 5 * 2 = 10
                            // Then x = 10

// Common mistake: thinking x becomes x * 2 * 2
// Actually: old value (5) is used in calculation

Mistake 4: Assigning incompatible types

// WRONG
int num = 7.5;              // double cannot fit in int

// CORRECT (requires casting, covered in 1.5)
int num = (int) 7.5;        // num gets 7

Mistake 5: Not checking for null before using reference variables

String text = null;
System.out.println(text.length());  // NullPointerException!

// Better approach
if (text != null) {
    System.out.println(text.length());
}

Practice Problems