Variables
A variable is a name given to a memory location. It is the basic unit of storage in a program.
- The value stored in a variable can change during program execution.
- A variable is just a name for a memory location — operations on the variable affect that memory location.
- In Java, all variables must be declared before use.
Types of Variables in Java
Now let us discuss different types of variables which are listed as follows:
- Primitive variables
- Reference variables
Primitive Variables: With primitive data types a variable is a section of memory reserved for a value of that type.
For example, declaring a long reserves 64 bits for an integer value.
The eight primitives in Java are: int, byte, short, long, float, double, boolean, char.
Examples:
int x;
byte b;
long l;
float f;
Reference Variables: A reference variable stores the address/reference of an object (not the object itself).
Example:
Student s = new Student();
Here s is a reference variable that refers to a Student object.
Local Variables
Local variables are declared inside a method, constructor or block. They are stored on the stack and exist only while the block executes.
Key points:
- Scope is the block where declared — destroyed when block completes.
- Local variables are thread-safe.
- JVM does not provide default values — local variables must be explicitly initialized before use.
- The only modifier allowed for local variables is final. Using access modifiers (public/private/etc.) on local variables will cause a compile error.
Example 1 (shows compile error if uninitialized):
class Test {
public static void main(String... args) {
int x;
System.out.print(x); // compile-time error: variable x might not have been initialized
}
}
Example 2 (valid — variable unused but program prints):
class Test {
public static void main(String... args) {
int x;
System.out.print("Hello"); // prints Hello
}
}
Example 3 (still compilation error if not guaranteed initialized):
class Test {
public static void main(String... args) {
int x;
if (args.length > 0) {
x = 20;
}
System.out.print(x); // compile-time error: x might not have been initialized
}
}
Only final is allowed as a modifier for local variables. Other modifiers like public/private/static on local variables are invalid.
Short summary
- Primitive: stores actual value (int, long, double, etc.).
- Reference: stores address to object (e.g. Student s = new Student()).
- Local: declared inside methods/blocks — must be initialized explicitly.
- Instance / Static: (covered in next section) — declared at class level and receive default values.