Java - Can final variables be initialized in static initialization block?

Yatendra picture Yatendra · Feb 26, 2010 · Viewed 36.7k times · Source

Based on my understanding of the Java language, static variables can be initialized in static initialization block.

However, when I try to implement this in practice (static variables that are final too), I get the error shown in the screenshot below:

https://i.stack.imgur.com/5I0am.jpg

Answer

SyntaxT3rr0r picture SyntaxT3rr0r · Feb 26, 2010

Yes of course: static final variables can be initialized in a static block but.... you have implicit GOTOs in that example (try/catch is essentially a 'GOTO catch if something bad happens').

If an exception is thrown your final variables will not be initialized.

Note that the use of static constructs goes against Object-Oriented dogma. It may complicate your testing and make debugging more difficult.