Yatendra Goel Yatendra Goel -4 years ago 125
Java Question

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.

Screenshot can be directly accessed at http://i49.tinypic.com/5vxfn4.jpg (in case the image below is unreadably small).

http://i49.tinypic.com/5vxfn4.jpg

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download