Declaring & initializing variables in Java
Type + name, assignment, definite assignment rule for locals.
A labeled box
A variable is a named box that holds one value of one type. Declaring it means writing the type and the name. Initializing it means giving it its first value, often on the same line.
int age; // declare
age = 30; // assign
int year = 2025; // both at oncePick the right type
int holds whole numbers, double holds decimals, boolean holds true or false, and String holds text. A decimal literal like 9.99 is a double, so an int can't hold it.
int count = 3;
double price = 9.99;
boolean ready = true;
String name = "Ada";Your turn
total was declared but never given a value. What happens?
int total;
System.out.println(total);0nullCompile error
Show the answer
Compile error: "variable total might not have been initialized". A local variable (one declared inside a method) gets no default value. You must assign it before reading it.
Definite assignment
Before a local variable is read, the compiler checks every possible path through the code. If any path could reach the read without an assignment, it's rejected. An if/else that assigns in both branches passes.
int x;
if (ready) {
x = 5;
} else {
x = 7;
}
System.out.println(x); // okYour turn
Does the compiler accept this? What does it print?
int x;
boolean big = false;
if (big) {
x = 100;
} else {
x = 1;
}
System.out.println(x);1100Compile error
Show the answer
Both branches assign x, so it's definitely assigned before the println. big is false, so the else branch runs and x is 1.
The missing else
If passed is false, score is never assigned, so the compiler rejects the println line. Fix it by initializing up front (int score = 0;) or by adding an else that assigns.
int score;
if (passed) {
score = 100;
}
System.out.println(score); // errorIn real projects
In C, an uninitialized local holds leftover bytes from memory: a source of baffling, random bugs that change from run to run. Java turns that whole category into a compile error, so it never reaches users.
Key takeaways
- Declaration: type + name
- Initialization: the first assignment, often on the same line
- Locals must be definitely assigned before they're read
The definite-assignment rules fill an entire chapter of the Java Language Specification (Chapter 16). That's how seriously Java takes "never read garbage".
Practice questions
Which type fits the blank?
___ price = 9.99;- int
- boolean
- char
- double
Check your answer
double. 9.99 is a decimal literal, which has type double. An int can't hold it without a cast.
What does this print?
int total;
System.out.println(total);- 0
- null
- Throws NullPointerException
- Compile error
Check your answer
Compile error. total is a local variable that was never assigned. javac reports "variable total might not have been initialized".