1

This Q rather for verification:

A static final field can be initialized when it's declared:

public static final int i=87;

or in the static block:

public static final int i;

//..........

static {
    ...
    i=87;
    ...

}

Is there anywhere, other than the static block, a static final field

public static final int i;

can be initialized?

Thanks in advance.

Note: saw Initialize a static final field in the constructor. it's not specific that the static block is the only place to initialized it outside the declaration.

//==============

ADD:

extending @noone's fine answer, in response to @Saposhiente's below:

mixing in some non-static context:

public class FinalTest {

private static final int INT = new FinalTest().test();

private int test() {
    return 5;
}
}
Community
  • 1
  • 1
Roam
  • 4,651
  • 9
  • 39
  • 71

4 Answers4

3

The Java Language Specification states

It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

So the answer to

Is there anywhere, other than the static block, a static final field can be initialized?

No, there isn't.

Sotirios Delimanolis
  • 263,859
  • 56
  • 671
  • 702
1

No. A field that is static belongs to the class, and a field that is final must be assigned by the time it becomes visible, so a static final field must be initialized either with the declaration or in a static initializer (which both get compiled to the same thing) so that it has a value when the class is finished loading.

chrylis -cautiouslyoptimistic-
  • 72,004
  • 20
  • 117
  • 147
1

It could be "initialized" in any random static method, but only indirectly by using the static block, or the variable initialization.

public class FinalTest {

    private static final int INT = test();

    private static int test() {
        return 5;
    }
}

Or like this:

public class FinalTest {

    private static final int INT;

    static {
        INT = test();
    }

    private static int test() {
        return 5;
    }
}

Technically, it is not really an initialization in test(), but it acts like one.

noone
  • 19,167
  • 5
  • 59
  • 75
0

It can only be initialized in a set of static code that is always run exactly once. This is usually in its declaration or in a static block, but you could also do something weird like

static final int i;
static int j = i = 1;

which is technically neither of those. Either way, you can't initialize it in any sort of function or constructor because that function might be run more than once; you have to use a static declaration or block of code to run the function and use the return value to initialize it.

Vitruvie
  • 2,311
  • 17
  • 24