Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems initializing a final variable in Java

Tags:

I keep running into slight variations of a problem in Java and it's starting to get to me, and I can't really think of a proper way to get around it.

I have an object property that is final, but dynamic. That is, I want the value to be constant once assigned, but the value can be different each runtime. So I declare the class level variable at the beginning of the class - say private final FILE_NAME;. Then, in the constructor, I assign it a value - say FILE_NAME = buildFileName();

The problem begins when I have code in the buildFileName() method that throws an exception. So I try something like this in the constructor:

try{    FILE_NAME = buildFileName(); } catch(Exception e){    ...    System.exit(1); } 

Now I have an error - "The blank final field FILE_NAME may not have been initialized." This is where I start to get slightly annoyed at Java's strict compiler. I know that this won't be a problem because if it gets to the catch the program will exit... But the compiler doesn't know that and so doesn't allow this code. If I try to add a dummy assignment to the catch, I get - "The final field FILE_NAME may already have been assigned." I clearly can't assign a default value before the try-catch because I can only assign to it once.

Any ideas...?

like image 794
froadie Avatar asked May 05 '10 13:05

froadie


People also ask

Can final variables be initialized in Java?

A blank final variable can be initialized inside an instance-initializer block or inside the constructor. If you have more than one constructor in your class then it must be initialized in all of them, otherwise, a compile-time error will be thrown.

Can final variables not be initialized?

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.

Can you set a final variable in Java?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.


1 Answers

How about

String tempName = null; try{    tempName = buildFileName(); } catch(Exception e){    ...    System.exit(1); } FILE_NAME = tempName; 
like image 99
Ryan Elkins Avatar answered Sep 27 '22 17:09

Ryan Elkins