Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
Wouldn't an uninitialized final variable always be blank because of its immutable nature?
closed

1 Answer

0 votes
by (11.3k points)
selected by
 
Best answer

No, you CAN assign a value to the final variable because final variables that haven't been assigned a value can only be assigned one when a constructor is called for initialization and no other way. Also, a final variable can only be assigned its final value with the help of a constructor call ONCE for a particular instance. 

Refer to the following code:

class abc{

final int a;

public abc(int b){

a=b;

}

public static void main(String arg[])

{

abc obj1=new abc(3);

abc  obj2=new abc(2);

System.out.println(obj1.a);

System.out.println(obj2.a);

System.out.println(obj1.a);

}}

Output:

3

2

3

As we can see here, we initialized the values of a for every instance through constructor. If we change the code slightly and make one small edit in the constructor code:

public abc(int b){

a=b;

a++; //addition

}

Output:

error: variable a might already have been assigned

a++;

This happens because after assigning the value of a once, we try to change it and that isn't possble in final variables.  

Related questions

Browse Categories

...