What is blank final variable with Example?

What is blank final variable with Example?

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.

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

publicclassEmployee

{

finaldoublesalary;// final blank variable

publicEmployee()// constructor

{

salary=9999.99;// value given in the constructor

}

publicstaticvoidmain(Stringargs[])

{

Employee emp1=newEmployee();// 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).

6. Does the following code compiles?

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

publicclassEmployee

{

finaldoublesalary;

publicEmployee()

{

salary=9999.99;

}

publicEmployee(doublex)

{

}

}

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

Java

1

2

3

4

publicEmployee(doublex)

{

salary=x;

}

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

Java

1

2

3

4

publicEmployee(doublex)

{

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.