Reference variables in Java can be declared in the following ways, but with different rules and implications depending on the context. Here's a breakdown:
static
variables (Class-level)
class Example {
static String staticRef = "Shared among all instances";
}
class Example {
String instanceRef = "Unique to each object";
}
void greet(String name) {
System.out.println("Hello, " + name);
}
void showMessage() {
String message = "Hello from local variable!";
System.out.println(message);
}
final
and reassigned, but the object they refer to can still be mutated unless the object itself is immutable.
In Java SE 22, instance variables refer to non-static fields declared inside a class but outside any method, constructor, or block. Each object (or instance) of the class gets its own copy of these variables.
✅ Definition
Instance variable = A variable that:
static
keyword
public class Car {
String color; // instance variable
int year; // instance variable
public Car(String color, int year) {
this.color = color;
this.year = year;
}
}
Car car1 = new Car("Red", 2022);
Car car2 = new Car("Blue", 2023);
car1
and car2
each have their own separate color
and year
values.car1.color
does not affect car2.color
.Feature | Instance Variable |
---|---|
Scope | Throughout the object’s lifetime |
Declared with static ? |
❌ No |
Memory Location | Heap (part of the object) |
Default Value | Yes (e.g., null , 0 , false ) |
Access | Can be private , protected , etc. |
Accessed via | Object reference (e.g., obj.var ) |
Type | Belongs To | Keyword | Lifetime |
---|---|---|---|
Instance Var | Each object | (none) | Object lifetime |
Static Var | The class itself | static |
Class lifetime |
Local Var | Method/block | (none) | During method |
Parameter Var | Method call | (none) | During call |
Local variables are variables declared within a method or block. A local variable is destroyed when the method has completed.
In Java, the lifetime of a local variable is strictly limited to the method or block in which it is declared.
✅ Definition of Local Variable
A local variable is:
if
, for
, etc.)
public void printMessage() {
String msg = "Hello!"; // local variable
System.out.println(msg);
}
msg
exists only during the execution of printMessage()
.msg
is destroyed, and its memory is eligible for garbage collection.Feature | Local Variable |
---|---|
Declared In | Method, constructor, or block |
Accessible In | Only within that method or block |
Lifetime | Begins when the block starts |
Destroyed When | The block/method exits |
Default Value | ❌ No — must be explicitly initialized |
Stored In | Stack memory, not heap |
void checkNumber(int x) {
if (x > 0) {
String msg = "Positive number"; // msg is scoped here
System.out.println(msg);
}
// System.out.println(msg); ❌ ERROR: msg not accessible here
}