Roam
Roam

Reputation: 4949

initializing a final field

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;
}
}

Upvotes: 1

Views: 1029

Answers (4)

Vitruvie
Vitruvie

Reputation: 2327

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.

Upvotes: 0

noone
noone

Reputation: 19776

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.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

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.

Upvotes: 3

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.

Upvotes: 1

Related Questions