Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42642

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?

Upvotes: 3

Views: 699

Answers (6)

Greg
Greg

Reputation: 1719

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'

Upvotes: 1

Jason
Jason

Reputation: 847

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

See java's official turorial.

Upvotes: 1

Robby Pond
Robby Pond

Reputation: 73484

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.

Upvotes: 2

Péter Török
Péter Török

Reputation: 116246

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.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370092

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

Upvotes: 10

GHad
GHad

Reputation: 9631

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

Upvotes: 1

Related Questions