What is blank final variable with Example?


1. What is blank final variable or uninitialized final variable?

A final variable declared but not assigned is known as a blank final variable or uninitialized final variable. Introduced with JDK 1.1.

2. How to initialize or give a value for an uninitialized final variable?

It is possible with a constructor call only. That is, the uninitialized final variable can be given a value through a constructor only (through method is not possible).

3. What is constructor blank variable?

A blank final variable given a value in the constructor is known as constructor blank variable.

4. Explain through an example?

Following is the example program to initialize a final blank variable.

public class Employee
{
  final double salary;				// final blank variable

  public Employee()				// constructor
  {
    salary = 9999.99;				// value given in the constructor
  }
  public static void main(String args[])
  {
    Employee emp1 = new Employee();		// constructor is accessed (or called)
    System.out.println(emp1.salary);           	// prints 9999.99
  }
}

5. If a blank final variable is not given a value in the constructor what happens?

It raises compilation error because a final blank variable should be given a value somewhere in the program and that too from a constructor only. In the above program, if "salary = 9999.99;" is commented out, compiler gives the following error (observe the screenshot).

ima

6. Does the following code compiles?

public class Employee
{
  final double salary;				

  public Employee()	
  {
    salary = 9999.99;
  }
  public Employee(double x)
  {

  }
}

In the above code, Employee constructor is overloaded. If overloaded, in each constructor salary must be initialized as follows.

  public Employee(double x)
  {
    salary = x;
  }

Or, atleast, a constructor can be called from another to get compiled.

  public Employee(double x)
  {
    this();
  }

7. What are the advantages of blank final variables?

Blank final variables allow the Programmer to make immutable data types. That is, final blank variables allow the class to declare immutable fields which are initialized at runtime by passing arguments to a constructor. Once assigned, the value cannot be changed accidentally.

2 thoughts on “What is blank final variable with Example?”

  1. Abhishek kumar singh

    Sir i want to know throw and throws keyword in java please expalin in detail not in bookish language

Leave a Comment

Your email address will not be published.