Variables and Primitive Types
Declare and initialize variables of type int, double, boolean, and char. Distinguish declaration from initialization and understand that uninitialized local variables cause compile errors. Explain int range (-2,147,483,648 to 2,147,483,647) and what happens at overflow (silent wraparound, not an exception). Apply implicit widening (int → double) and explicit narrowing casts ((int) 3.9 = 3, truncates toward zero). Use final for constants. Apply Java naming conventions (camelCase, no spaces, starts with letter).
A lesson of AP Computer Science A, in Java Foundations, about 10 minutes.
Variables and Data Types in Java
By the end of this lesson, you will be able to declare and initialize variables of the three AP-tested types, perform arithmetic, understand integer division, and use the Math class.
Declaring Variables
type variableName; // declaration only
type variableName = value; // declaration + initialization
variableName = value; // assignment (variable must already exist)
Java is statically typed: every variable has a type declared at compile time.
The Three AP-Tested Primitive Types
int count = 0;
int score = -15;
int year = 2024;
int: integers (whole numbers). Range: about ±2.1 billion.
double: floating-point numbers (decimals). 64-bit precision.
double pi = 3.14159;
double gpa = 3.8;
double temperature = -12.5;
boolean: true or false only.
boolean isStudent = true;
boolean finished = false;
String (a Class, not a Primitive)
String name = "Alice"; // double quotes
String empty = ""; // empty string
String greeting = "Hi " + name; // concatenation
String is a class (capital S), not a primitive — it has methods, uses == incorrectly for comparison (use .equals()), and can be null.
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 10 - 4 = 6 |
* | Multiplication | 3 * 7 = 21 |
/ | Division | 10 / 3 = (integer!) |