Final Instance Variable
- If the value of a variable changes from object to object, such a variable is called an instance variable.
- For every object, a separate copy of the instance variable will be created.
- Instance variables do not require explicit initialization; JVM always provides default values.
class Test {
int x; // instance variable
public static void main(String... args) {
Test t = new Test();
System.out.println(t.x); // output: 0
}
}
- If the instance variable is declared as final, then explicit initialization is mandatory. JVM will NOT provide default values.
class Test {
final int x;
}
Compile-time Error: variable x might not have been initialized.
Rule: A final instance variable must be initialized before constructor completion.Possible places for initialization:
- 1. At the time of declaration
class Test {
final int x = 10;
}
- 2. Inside an instance block
class Test {
final int x;
{
x = 10;
}
}
- 3. Inside the constructor
class Test {
final int x;
Test() {
x = 10;
}
}
These are the only valid places for initialization. Assigning anywhere else results in an error.
Invalid Example:
class Test {
final int x;
public static void m() {
x = 10; // Invalid
}
}
Compile-time Error: cannot assign a value to final variable x.
Final Static Variables
If a variable's value does not vary from object to object, it should be declared at the class level using the static modifier.
Static variables have a single copy shared among all objects and are automatically given default values by the JVM.
Example:
class Test {
static int x;
public static void main(String... args) {
System.out.println(x); // output: 0
}
}
If a static variable is declared as final, then explicit initialization is mandatory.
Example:
class Test {
final static int x;
}
Compile-time Error: variable x might not have been initialized.
Rule: A final static variable must be initialized before class loading completes.Possible places for initialization:
- 1. At the time of declaration
class Test {
final static int x = 10;
}
- 2. Inside a static block
class Test {
final static int x;
static {
x = 10;
}
}
These are the only valid places. Assigning anywhere else causes an error.
Invalid Example:
class Test {
final static int x;
public void m() {
x = 10; // Invalid
}
}
Compile-time Error: cannot assign a value to final variable x.
Final Local Variables