Variables

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:

  • Data type (what kind of data it stores)
  • Name (identifier)
  • Value

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 


Practical
Implementation
In everyday coding, you will most likely use inline initialization, which performs all three steps at once:
// Declaration, Definition, and Initialization in one go
double price = 19.99;
int age = 20;
double salary = 5000.50;
String name = "Ali";

// Separate steps
String name;           // Declaration
name
= "Gemini";       // Initialization
Clear Comparison Table

Simple Analogy

Think of a variable like a box:
Declaration You label the box (int age)
Definition The box is created in memory
Initialization You put something inside the box (20)
Key Rules to Remember
Local Variables: Must be initialized before use, or the code won't compile.
Instance Variables: (Fields in a class) get a default value (like 0, false, or null) if you don't initialize them manually.
The final Keyword: If you initialize a final variable, its value becomes a constant and cannot be changed later.