Getting Started
A program's power comes from its ability to work with data that can change. To write useful and interactive software, we need two fundamental tools: a way to store and update information within the program, and a way to get new information from a user. This chapter covers how Java uses assignment statements to manage data and the Scanner class to read user input.
What You Should Be Able to Do
Evaluate a Java expression and assign its resulting value to a variable.
Use the assignment operator (
=) to change the value stored in a previously declared variable.Write code to create a
Scannerobject to accept input from the keyboard.Use
Scannermethods to read and store user-provided integers, decimal numbers, and strings.Trace the changing values of variables as a sequence of assignment statements executes.
Key Concepts & Java Implementation
The Core Idea
In programming, a variable is a named location in memory that holds a value. The primary way to place a value into a variable is through an assignment statement. The assignment operator in Java is the equals sign (=).
A critical rule to remember is that the code on the right-hand side of the = is always evaluated first. The result of that evaluation is then stored in the variable on the left-hand side. This right-hand side, known as an expression, can be a simple value (like 10), another variable (like score), or a complex calculation (like price * 1.06).
To make programs interactive, we need to get data from outside the program itself. In Java, a common way to read keyboard input is by using the Scanner class. You create a Scannerobject—a specific instance of the class that has its own data and behaviors—which connects to an input source like the keyboard. You can then use methods from that object to read different types of data.
Syntax & Implementation
Assignment Statements
The assignment operator (=) copies the value from the right side into the variable on the left.
| Syntax Element | Purpose | Java Example |
|---|---|---|
variable = expression; | Evaluates the expression on the right and stores its single resulting value in the variable on the left. | int finalScore = 100; |
// Annotated Example: Basic Assignment
// 1. Declare an integer variable named 'players'.
int players;
// 2. Assign the literal value 10 to 'players'.
players = 10; // 'players' now holds the value 10.
// 3. Assign a new value calculated from an expression.
// The right side (players * 2) is evaluated first (10 * 2 = 20).
// The result (20) is then assigned to 'players'.
players = players * 2; // 'players' now holds the value 20.
// 4. Assign the value of one variable to another.
int maxScore = 950;
int userScore = maxScore; // 'userScore' is assigned a copy of the value in 'maxScore'.
// 'userScore' is now 950.
Reading User Input with Scanner
To read input, you must first import the Scanner class and then create a Scanner object.
A constructor is a special method that is called to create an object. The syntax new Scanner(System.in) calls the Scanner constructor to create a new Scanner object that reads from the standard input stream (the keyboard).
// Annotated Example: Reading Different Data Types
// 1. Make the Scanner class available to your program.
import java.util.Scanner;
public class UserProfile {
public static void main(String[] args) {
// 2. Create a Scanner object to read from the keyboard.
Scanner inputReader = new Scanner(System.in);
// 3. Prompt the user for their name.
System.out.println("Enter your name: ");
// 4. Read the next word of text and assign it to the 'name' variable.
String name = inputReader.next();
// 5. Prompt the user for their age.
System.out.println("Enter your age: ");
// 6. Read the next integer and assign it to the 'age' variable.
int age = inputReader.nextInt();
// 7. Prompt the user for their GPA.
System.out.println("Enter your GPA: ");
// 8. Read the next double and assign it to the 'gpa' variable.
double gpa = inputReader.nextDouble();
// 9. Print the collected information.
System.out.println("Profile Created: " + name + ", age " + age + ", GPA: " + gpa);
}
}
Tracing & Analysis
Execution Trace
Tracing variable values is a key skill for understanding and debugging code. Let's trace a common "swap" routine.
Code:
int x = 10;
int y = 25;
int temp;
temp = x;
x = y;
y = temp;
Trace Table:
| Line of Code Executed | Value of x | Value of y | Value of temp |
|---|---|---|---|
| (Before execution) | uninitialized | uninitialized | uninitialized |
int x = 10; | 10 | uninitialized | uninitialized |
int y = 25; | 10 | 25 | uninitialized |
int temp; | 10 | 25 | uninitialized |
temp = x; | 10 | 25 | 10 |
x = y; | 25 | 25 | 10 |
y = temp; | 25 | 10 | 10 |
| (After execution) | 25 | 10 | 10 |
Analysis
The data type of the expression on the right side of an assignment must be compatible with the data type of the variable on the left. For example, you cannot directly assign a double value to an int variable because it could result in a loss of precision (the decimal part would be truncated). The compiler will report an error.
int value = 9.99; // This will cause a compile-time error.
Java Syntax Quick-Reference
A summary of the new syntax introduced in this topic.
| Syntax | Description |
|---|---|
variable = expression; | The assignment statement. Assigns the result of expression to variable. |
import java.util.Scanner; | A required statement placed at the top of a file to use the Scanner class. |
new Scanner(System.in) | Creates a Scanner object configured to read from the keyboard. |
scannerObject.nextInt() | A method that reads the next token of user input as an int. |
scannerObject.nextDouble() | A method that reads the next token of user input as a double. |
scannerObject.next() | A method that reads the next token of user input (up to a space) as a String. |
Core Code Examples & Terminology
Assignment Operator (
=): The operator used to assign the value of an expression on its right to the variable on its left.Expression: A combination of values, variables, operators, and method calls that evaluates to a single value.
Object: A specific instance of a class, with its own state (data) and behavior (methods).
inputReaderin the example is an object.Constructor: A special method used to initialize a newly created object.
new Scanner(...)invokes theScannerconstructor.Scanner: A Java class that provides methods for reading input from various sources, including the keyboard.Core Snippet 1 (Sequential Assignment):
int a = 50; int b = 100; a = b; // 'a' now holds 100. 'b' is unchanged.This demonstrates that assignment copies a value; it does not link the variables.
Core Snippet 2 (Reading an Integer):
import java.util.Scanner; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); int userNum = keyboard.nextInt();This is the standard pattern for creating a
Scannerand reading an integer from the user.
Core Skill Check
Code Tracing: What is the final value of
yafter this Java code runs:int x = 5; int y = 10; y = x; x = 20;?- Answer: 5
Debugging: Identify the compile-time error in this Java code:
double cost = 15.50; int price = cost;.- Answer: Type mismatch; you cannot assign a
doubleto anintwithout an explicit cast.
- Answer: Type mismatch; you cannot assign a
Application: Write a single line of Java code that creates a
Scannerobject namedconsolethat reads from the keyboard.- Answer:
Scanner console = new Scanner(System.in);
- Answer:
Common Misconceptions & Errors
Confusing Assignment (
=) with Equality (==): The single equals sign (=) assigns a value. The double equals sign (==) compares two values. Using=in a conditional statement is a common error.Forgetting to Import
Scanner: If you use theScannerclass without includingimport java.util.Scanner;at the top of your file, the compiler will not know whatScanneris and will produce an error.Variables are Not Linked: After
x = y;, the variablesxandyare independent. Changingylater will not affectx, and vice-versa. The assignment performs a one-time copy of the value.Input Type Mismatch: If you prompt the user for a number but they type text (e.g., "hello"), calling
.nextInt()or.nextDouble()will cause your program to crash with anInputMismatchException.
Summary
This topic introduced the core mechanics for making programs dynamic and interactive. The assignment operator (=) is the fundamental tool for storing and updating data in variables, always working by evaluating the expression on the right and copying its result into the variable on the left. To get data from a user, we use the Scanner class. By creating a Scanner object, we gain access to methods like .nextInt(), .nextDouble(), and .next(), which allow our programs to read keyboard input. Combining user input with assignment statements allows us to write flexible programs that can operate on different data each time they are run.