Instance variable: As we all know, when the value of a variable varies from object to object, this type of variable is called an instance variable. Instance variables are declared in the class, but not in any methods, constructors, blocks, etc. If we do not initialize the instance variable, the JVM will automatically provide a default value based on the data type of the instance variable. But if we declare an instance variable as final, then we must care about the behavior of the instance variable.
// Java program to illustrate the behavior // of final instance variable class Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } }
Output:
error: variable x not initialized in the default constructor
2. Initialization before constructor completion :
// Java program to illustrate that // final instance variable // should be declared at the // time of declaration class Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } }
Output:
10
3. Initialize inside a non-static or instance block :
// Java program to illustrate // that final instance variable // can be initialize within instance block class Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } }
Output:
10
4. Initialization in default constructor :
Inside default constructor we can also initialize a final instance variable.
// Java program to illustrate that // final instance variable // can be initialized // in the default constructor class Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } }
Output:
10
The above is the only possible place to initialize the last instance variable. If we try to initialize it elsewhere, we get a compile time error.
// Java program to illustrate // that we cant declare // final instance variable // within any static blocks class Test { final int x; public static void main(String[] args) { x = 10; Test t = new Test(); System.out.println(t.x); } }
Output:
error: non-static variable x cannot be referenced from a static context