In this lesson, we explore two fundamental pillars of programming: assignment statements (how values flow into variables) and input (how programs receive data from users). Understanding these concepts is essential for writing interactive, dynamic programs.

We’ll start by learning the concepts through detailed explanations, then apply them in code examples with real-world scenarios, and finally reinforce understanding with interactive practice problems.

Learning Objectives

By the end of this lesson, you will be able to:

  • LO 1.4.A: Develop code for assignment statements with expressions and determine the value stored in variables.
  • LO 1.4.B: Develop code to read input using the Scanner class.

You’ll understand how data flows in programs, how to make them interactive, and common pitfalls to avoid when working with user input.

Essential Knowledge

  • 1.4.A.1: Every variable must be assigned a value before use. The value’s type must match the declared type. Reference types can hold an object or null.
  • 1.4.A.2: The assignment operator = stores the result of the right-hand expression into the left-hand variable.
  • 1.4.A.3: Expressions are evaluated to a single value before assignment occurs.
  • 1.4.B.1: Input in Java is commonly handled by the Scanner class for reading keyboard data.

Part 1: Assignment Statements

Understanding Variable Assignment

In Java, variables are named memory locations that store values. Think of them as labeled boxes in the computer’s memory. Before using a variable, you must:

  1. Declare it with a specific type (int, double, String, etc.)
  2. Assign it a value using the = operator

The assignment operator works right to left: it evaluates the expression on the right side first, then stores that result in the variable on the left.

// Declaration and initialization
int a = 5;           // 'a' stores the integer 5
int b = 3;           // 'b' stores the integer 3
int c = a + b;       // Expression 'a + b' evaluates to 8, then stored in 'c'

// Reassignment: old value is completely overwritten
int x = 10;          // 'x' holds 10
x = 20;              // 'x' now holds 20 (10 is gone)
x = x + 5;           // Right side: x + 5 = 20 + 5 = 25, then stored back in x

// Reference types and null
String name = null;  // 'name' declared but points to no object
name = "Ahaan";      // 'name' now references a String object containing "Ahaan"

Key Insight: Expression Evaluation

The critical concept here is order of operations. Java always:

  1. Evaluates the entire right-hand expression first
  2. Then performs the assignment

This is why x = x + 5; works: Java reads the current value of x, adds 5, then stores the result back into x.

Popcorn Hack 1.1: Tracing Variable Values

Question: After executing this code, what is the value of y? Walk through each line.

int x = 10;
x = 20;
int y = x;
Answer y is 20. Here's why: - Line 1: x is assigned 10 - Line 2: x is reassigned to 20 (the 10 is overwritten) - Line 3: The current value of x (which is 20) is copied into y

Popcorn Hack 1.2: Type Safety

Question: What happens if you write int count = "hello";? Why does this fail, and why is this behavior actually helpful?

Answer This produces a compile-time error. Java is strongly-typed, meaning the type of the value must match the variable's declared type. An int can only hold integer values, not strings. This "strictness" prevents bugs—if Java allowed this, mathematical operations on count would fail unpredictably at runtime.

Part 2: Input with Scanner

Why Input Matters

Hardcoded values make programs static and inflexible. Real applications need to respond to user data dynamically. Java’s Scanner class provides a robust mechanism for reading various data types from input streams.

Setting Up Scanner

Two steps are required:

  1. Import the class at the top of your file:
    import java.util.Scanner;
    
  2. Instantiate a Scanner object connected to standard input:
    Scanner sc = new Scanner(System.in);
    

The System.in parameter connects the Scanner to your keyboard input stream.

Reading Different Data Types

Scanner provides type-specific methods for reading input:

import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // Reading a String (entire line)
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Hello, " + name + "!");
        
        // Reading an integer
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        System.out.println("You entered: " + age);
        
        // Reading a double
        System.out.print("Enter a decimal: ");
        double value = sc.nextDouble();
        System.out.println("Double that is: " + (value * 2));
        
        sc.close();  // Always close to prevent resource leaks
    }
}

Scanner Methods Overview

The Scanner class provides several methods for reading different types of input:

  • nextInt() - Reads the next integer value (e.g., 42)
  • nextDouble() - Reads the next decimal number (e.g., 3.14)
  • next() - Reads the next word up to whitespace (e.g., "Hello")
  • nextLine() - Reads an entire line including spaces (e.g., "Hello World")

Critical Pitfall: The nextInt() / nextLine() Problem

This is one of the most common stumbling blocks for Java beginners. Understanding it requires knowledge of how input buffers work.

The Problem: When you call nextInt(), nextDouble(), or next(), these methods read only their specific token (the integer, double, or word). Critically, they do not consume the newline character (\n) that’s created when the user presses Enter. This leftover newline sits in the input buffer.

If you then call nextLine(), it immediately encounters this leftover newline, interprets it as an empty line, and returns an empty string without waiting for user input.

Visual Example:

Input Buffer: [2][5][\n][R][e][m][a][i][n][i][n][g]...
              ↑
nextInt() reads "25" but leaves [\n] behind

nextLine() immediately consumes [\n] and returns ""

The Solution: Insert an extra sc.nextLine(); call immediately after nextInt() or nextDouble() to consume the leftover newline before reading a full line.

Scanner sc = new Scanner(System.in);

System.out.print("Enter your age: ");
int age = sc.nextInt();

// FIX: Consume the leftover newline character
sc.nextLine();

System.out.print("Enter your full name: ");
String fullName = sc.nextLine();  // Now waits for input correctly

System.out.println("Hello, " + fullName + "! You are " + age + " years old.");
sc.close();

Popcorn Hack 2.1: Input Validation

Question: What happens if a user types “twenty” when nextInt() expects a number? How would you make your program more robust?

Answer A java.util.InputMismatchException is thrown because nextInt() cannot parse non-numeric text. To make it robust: - Use hasNextInt() to check if the next token is an integer before reading - Or use nextLine() to read as String, then parse with Integer.parseInt() in a try-catch block

Popcorn Hack 2.2: Token vs Line

Question: If a user enters “San Diego” when next() is called, what gets stored? What about with nextLine()?

Answer - next() stores only "San" because it reads until whitespace. "Diego" remains in the buffer. - nextLine() stores "San Diego" because it reads everything until the newline character (Enter key).

Part 3: Complete Working Example

Here’s a comprehensive example demonstrating proper input handling:

import java.util.Scanner;

public class InputLesson {
    public static void main(String[] args) {
        System.out.println("=== User Information Program ===\n");
        Scanner sc = new Scanner(System.in);

        // String input
        System.out.print("Enter your full name: ");
        String name = sc.nextLine();
        
        // Integer input
        System.out.print("Enter your age: ");
        int age = sc.nextInt();
        
        // Double input
        System.out.print("Enter your GPA: ");
        double gpa = sc.nextDouble();
        
        // Display results
        System.out.println("\n--- Summary ---");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age + " (next year: " + (age + 1) + ")");
        System.out.println("GPA: " + gpa);
        
        sc.close();
    }
}

Popcorn Hack 3: Code Trace

Question: Trace through the complete example. If the user enters “Alice Wonderland”, 20, and 3.85, what is the exact output?

Answer === User Information Program === Enter your full name: Alice Wonderland Enter your age: 20 Enter your GPA: 3.85 --- Summary --- Name: Alice Wonderland Age: 20 (next year: 21) GPA: 3.85

Quick Knowledge Check

Q1. What is the value of x after this code executes?

int x = 4;
x = x + 3;

A. 4
B. 7
C. 3
D. null

Answer B. The expression x + 3 evaluates to 4 + 3 = 7, which is then stored in x.

Q2: Which statement(s) correctly declare and initialize a String variable?

A. String s = 5;
B. String s = null;
C. String s = "Hello";
D. Both B and C

Answer Both B and C are valid. null is a valid value for reference types, and "Hello" is a String literal.

Homework Hacks: Pick One to Complete

Hack 1: Three-Number Average Calculator

Task: Modify the example program to:

  • Prompt for three integers
  • Calculate their average (watch for integer division!)
  • Display the result with two decimal places

Hint: Cast at least one number to double before division: (double) num1 / 3

Hack 2: Assignment vs Comparison Explanation

Task: Write an explanation distinguishing between:

  • Assignment operator (=)
  • Comparison operator (==)

Include code examples showing proper usage of each. Explain a common bug that occurs when these are confused.


The goal of this lesson is to teach you two key concepts:

  1. How to assign values to variables and understand how expressions are evaluated
  2. How to take in user input and use them in your program to create interactive applications

These foundational skills will enable you to create dynamic programs that respond to user data rather than relying on hardcoded values.

8. Interactive Quiz Game

Finally, here’s a fun quiz game built in JavaScript + HTML to test your knowledge of assignment statements, input, and how they connect to the lesson. Play through it and check your understanding!

1.3 and 1.4 Game