Search code examples
javastaticfinal

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


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.sstatic.net/5I0am.jpg


Solution

  • 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.