Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with constants in static block java

I have two questions regarding the static block and Constants with below code.

  1. Constant (or even simple Static variable) cannot be directly referrenced from static block. It gives error saying "Cannot reference a field before it is defined". But it is ok when accessing through a static method.
  2. If I assign a value to a constant in static block's catch as mentioned below it gives error saying "The final field NAME may already have been assigned". But if asigning in catch it gives error saying "The blank final field NAME may not have been initialized".

I want to know why is it bahaving like this?

Code :

public class TestStaticblock {

    static{
        try {
//          NAME = dummyStringValue() + NAME_APPENDER; // Cannot reference a field before it is defined
//          NAME = dummyStringValue() + getNameAppender(); // This is OK

            NAME = dummyStringValue();
        } catch (Exception e) {
            NAME = null; // The final field NAME may already have been assigned
        }
    }

    private static String dummyStringValue() throws Exception{
        return "dummy";
    }

    private static String getNameAppender() throws Exception{
        return NAME_APPENDER;
    }

    private static final String NAME; // If I comment Catch it says "The blank final field NAME may not have been initialized"
    private static  String NAME_APPENDER = "appender";

}
like image 779
namalfernandolk Avatar asked Sep 15 '26 00:09

namalfernandolk


1 Answers

You can only assign to NAME once (because it is final). Assign the result to a temporary variable, and then assign to NAME (and don't silently swallow Exceptions). Something like,

static {
    String temp = null;
    try {
        temp = dummyStringValue();
    } catch (Exception e) {
        e.printStackTrace();
    }
    NAME = temp;
}

The reason you can't assign NAME the way your are currently is because the compiler performs static program analysis (specifically, the data-flow analysis) and that detects that there is a possible code path where NAME is not assigned. And because NAME is final, that is a compilation error.

like image 169
Elliott Frisch Avatar answered Sep 16 '26 14:09

Elliott Frisch