Variables in Java
A variable is a name given to a memory location used to store data.
- Value can change during execution
- Represents memory location
- Must be declared before use
Types of Variables
- Primitive
- Reference
Primitive Variables: Store actual values.
Types: int, byte, short, long, float, double, boolean, char
int x = 10;
float f = 5.5f;
Reference Variables: Store object reference.
Student s = new Student();
Program Output
Variables are also classified as Local, Instance, and Static.
Local Variables
- Declared inside methods
- No default value
- Must initialize before use
- Stored in stack memory
int x;
System.out.println(x); // error
Instance Variables
- Declared inside class but outside methods
- Each object has its own copy
- Default values provided by JVM
class Student {
int id;
}
Static Variables
- Declared using static keyword
- Shared among all objects
- Stored in method area
class Test {
static int count = 0;
}
Comparison Table
| Type | Scope | Default Value | Memory |
|---|---|---|---|
| Local | Method | No | Stack |
| Instance | Object | Yes | Heap |
| Static | Class | Yes | Method Area |
Example Program
class Test {
static int a = 10;
int b = 20;
public static void main(String[] args) {
int c = 30;
System.out.println(a + " " + c);
}
}
Summary
- Primitive → stores value
- Reference → stores address
- Local → no default value
- Instance → object-level
- Static → class-level shared
0 Comments
Hello