Variables in Java
A variable is a named piece of memory that holds a value of one specific, declared type. Declaring a variable reserves storage shaped for that type; assigning to it stores an actual value there. Unlike Python, you can't just assign into a name and have it spring into existence — Java requires a type to be stated up front (or inferred with var), and that type never changes for the life of the variable.
Declaration and initialization can happen together or separately: int age; followed later by age = 25; does the same thing as int age = 25; written on one line. Since Java 10, the var keyword lets the compiler infer a local variable's type from whatever is assigned to it — var age = 25; still makes age a genuine, fixed int underneath. var is a shortcut for writing the type, not a step toward dynamic typing.
Declare
int age; reserves storage sized for an int and names it age, with no value stored yet.
Initialize
age = 25; stores an actual value into that reserved space. Declaring and initializing can also be combined into one line: int age = 25;
The type is fixed at declaration
Once age is declared as an int, it can only ever hold int values for the rest of its life.
Reassignment
age = 30; overwrites the previous value in the same memory location — only the contents change, not the variable's identity or type.
Type inference with var
var age = 25; lets the compiler infer int from the right-hand side, but age ends up exactly as statically typed as if int had been written by hand. var needs an initializer to infer from, and can never later hold a different type.
public class VariableDemo { public static void main(String[] args) { int age; age = 25; var name = "Ada"; System.out.println(name + " is " + age); age = 26; System.out.println(name + " is now " + age); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.