Java Variables and Its Types
1. What is a Variable in Java?
A variable in Java named
is a memory location
used to store data values during program execution. The
value of a variable can change while the program is running.
Syntax:
DataType variableName = value;
Example:
int age = 21;
Here: - int → data type - age → variable name - 21 → value
2. Types of Variables in Java
Java variables are mainly classified into three types based on their scope and lifetime:
1. Local Variables
2. Instance Variables
3. Static Variables
3. Local Variables
• Declared inside a method, constructor, or block
• Scope is limited to the method or block
• Must be initialized before use
• Stored in stack memory
Example:
class Test {
void display() {
int x = 10; // local variable
[Link](x);
1
}
}
4. Instance Variables
• Declared inside a class but outside any method
• Each object gets its own copy
• Default values are provided by Java
• Stored in heap memory
Example:
class Student {
int rollNo; // instance variable
String name; // instance variable
}
5. Static Variables
• Declared using the static keyword
• Shared among all objects of the class
• Only one copy exists
• Stored in method area
Example:
class College {
static String collegeName = "ABC College"; // static variable
}
6. Summary Table
Variable Type Declaration Place Scope Memory Default Value
Local Inside method/block Method only Stack No
Instance Inside class Object level Heap Yes
Static Inside class with static Class level Method area Yes
2
7. Conclusion
Variables are fundamental building blocks of Java programs. Understanding the types of variables a
scope helps in writing efficient, memory-optimized, and well-structured Java code.