Java instance variable as final

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.

  • We have to use instance variable as final within the creation of immutable class.
Important points about final instance variable:
 
  1. Initialization of variable Mandatory : If the instance variable declared as final, then we've to perform initialization explicitly whether we are using it or not and JVM won’t provide any default value for the ultimate 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

 

Submit Your Programming Assignment Details