In Java, understanding how a variable comes into existence involves three distinct steps. While we often perform them in a single line of code, they represent different actions within the Java Virtual Machine (JVM).
Every variable has:
The Core Concepts
Declaration
This is where you tell the compiler about the name and the data type of the variable. It allocates no memory for the value itself, only space in the symbol table to track the variable's existence.
Syntax: dataType variableName;
Example: int speed;
Definition
In many languages (like C++), "definition" and "initialization" are distinct.
In Java, definition is effectively the combination of declaration and the allocation of memory.
For primitive types, declaration is the definition. For objects, the definition happens when the memory is allocated on the heap.
Initialization
This is the act of assigning an initial value to the variable. Until a local variable is initialized, it cannot be used.
• Syntax: variableName = value;
• Example: speed = 60;
Side-by-Side Comparison