Java Variable
Published: (December 18, 2025 at 12:45 AM EST)
2 min read
Source: Dev.to
Source: Dev.to
Why use variables
- Store data temporarily in memory
- Reuse values multiple times
- Perform calculations
- Make programs dynamic and flexible
- Improve code readability and maintenance
How a variable is created in Java
1. Declaration (Memory allocation)
int age;
- Tells Java what type of data to store
- Reserves memory for the variable
2. Initialization (Assign value)
int age = 25;
- Stores the value in the allocated memory
When is a variable created?
Local Variable
- Where created? Inside a method or block
- When created? When the method/block is entered
- When destroyed? When the method/block exits
- Memory location: Stack
void show() {
int x = 10; // local variable
}
- Must be initialized before use
- No default value
Instance Variable (Non‑static)
- Where created? As a member of a class instance
- When created? When an object is instantiated (
new) - When destroyed? When the object is garbage‑collected
- Memory location: Heap
class Student {
int id; // instance variable
}
Student s = new Student(); // instance variable created here
- Receives a default value if not explicitly initialized
Static Variable (Class Variable)
- Where created? Inside a class with the
statickeyword - When created? When the class is loaded by the JVM
- When destroyed? When the JVM shuts down
- Memory location: Method Area (Class Area)
class College {
static String collegeName = "ABC College";
}
- A single copy is shared by all objects of the class
Parameter Variable
- Where created? In a method’s parameter list
- When created? When the method is invoked
- Memory location: Stack
void add(int a, int b) {
int sum = a + b; // 'a' and 'b' are parameter variables
}