简体   繁体   中英

Initialize static final variable

I was wondering, what is there any different, on various ways to initialize static final variable?

private static final int i = 100;

or

private static final int i;
static {
    i = 100;
}

Is there any different among the two?

If you're only setting variables, both forms are equivalent (and you should use the former as it is more readable and succinct).

The static {} form exists for cases where you also need to execute statements other than variable assignments. (Somewhat contrived) example:

private static final int i;
static {
    establishDatabaseConnection();
    i = readIntFromDatabase;
    closeDatabaseConnection();
}

静态块的主要原因是能够在初始化中添加一些逻辑,而不是在1行初始化中进行,例如初始化数组或其他东西。

Yes, by using the second way you are able to use a try...catch block and react to exceptions where as with the first way declared exceptions cannot be catched.

There is also a difference when at class init the fields and die static block is executed but I have no details, see language specification on class instantiation for more information.

Greetz, GHad

For a primitive variable, nothing. The difference can be if the initialization is not trivial, or the init method / constructor throws a checked exception - then you need a static block in order to be able to handle the exception.

They are the same except you can write multiple lines in the static code block.

See java's official turorial .

You could also use Forward Reference initialization

public class ForwardReference {
private static final int i  = getValue();
private static final int j = 2;
public static void main(String[] args) {
    System.out.println(i);
}

private static int getValue() {
    return j*2;
}

}

The key here is that we are getting value of 'j' from 'getValue' before 'j' have been declared. Static variables are initialized in order they appear.

This will print correct value of '4'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM