Initialization of a static final variable

I was wondering what are the different ways to initialize a static final variable?

private static final int i = 100;

or

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

Is there any other of the two?

+3
source share
6 answers

If you only set variables, both forms are equivalent (and you should use the first, as it is more readable and multiple).

A form static {}exists for cases where you also need to follow instructions other than variable assignments. (A little far-fetched) example:

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

, 1 , - .

+2

, , try... catch , , , .

, init die, , . .

Greetz, GHAD

+1

. , , / init - static, .

+1

They are the same, except that you can write multiple lines in a static block of code.

See java official tour. .

+1
source

You can 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 point here is that we get the value of 'j' from 'getValue' before declaring 'j'. Static variables are initialized so that they are displayed.

This will print the correct value "4"

+1
source

Source: https://habr.com/ru/post/1752827/


All Articles