Unit 1.4
Assignment Statements and Input
AP Computer Science A
What we'll learn: How to store values in variables and get input from users
Variable Initialization
Every variable must be assigned a value before it can be used in an expression.
A variable is initialized the first time it is assigned a value.
int x; // Declaration only - not initialized!
// System.out.println(x); // ERROR! Can't use x yet
int y = 5; // Declaration AND initialization
System.out.println(y); // OK! y has a value
x = 10; // Now x is initialized
System.out.println(x); // OK! x now has a value
The Assignment Operator (=)
The assignment operator = allows a program to initialize or change the values stored in a variable.
The value of the expression on the right is stored in the variable on the left.
int score = 85; // Initialize score to 85
score = 90; // Change score to 90
score = score + 5; // Use current value in expression
// score is now 95
String name = "Alice"; // Initialize name
name = "Bob"; // Change name to "Bob"
Expression Evaluation
During execution, an expression is evaluated to produce a single value.
The value of an expression has a type based on the evaluation.
int result = 3 + 4 * 2; // Evaluates to 11 (not 14!)
double average = (85 + 92 + 78) / 3.0; // 85.0
boolean passed = average >= 70; // true
String greeting = "Hello" + " " + "World"; // "Hello World"
Reading Input with Scanner
Input can come in various forms: tactile, audio, visual, or text.
The Scanner class is one way to obtain text input from the keyboard.
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Enter your age: ");
int age = input.nextInt();
System.out.print("Enter your GPA: ");
double gpa = input.nextDouble();
System.out.println("Hello " + name + "!");
Summary & Key Points
- Variables must be initialized before use
- Assignment operator = stores right-side value in left-side variable
- Expressions are evaluated to produce a single typed value
- Reference types can be assigned objects or null
- Scanner class helps read text input from keyboard
Practice: Try writing code that declares variables, assigns values using expressions, and reads user input with Scanner!
1 / ?