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开发者_如何学Go {
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();
}
The main reason for the static blocks are to be able to add some logic to the initialization that you cannot do in the 1 line initialization, like initializing an array or something.
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'
精彩评论