Mohan
Mohan

Reputation: 1955

static block vs private static method for static member initialization

A static variables can be initialized with the private static methods or with a static block. Are there any subtle difference between the two? Are there any situation where I cannot use the static method for initializing static members? I found the later more readable.

Static Block initialization :

private static int NUM_ITER;
static {
    // Operations
    NUM_ITER = //val from above operations.
}

Private static method initialization:

private static int NUM_ITER = calculateNumIter();

// Some method comment on how we are calculating.
private static int calculateNumIter()
{
    // Operations.
    return //value_from_operations.
}

I prefer the second one since it is more readable. Are there any situation I have to use only first (static blocks) ?

What is the best coding convention/design for initializing static members(final as well as variable)? Even from this thread I learned private static methods have an advantage over the static blocks.

thanks,

Upvotes: 13

Views: 2754

Answers (3)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

  1. static Initializer block (Your 1 option) executes when the JVM loads the class, even before any static variable is initialized.

  2. Its a good place to have all the static variables at once.

  3. Your second option can be optionally used to initialize multiple static variables by passing multiple arguments to the parameter of the initializing method.

Upvotes: 1

Matteo Caprari
Matteo Caprari

Reputation: 2979

I would suggest to use whatever syntax keeps your code clean and readable:

  • if the initialization amounts to one, max two, very simple lines of code, then go with the static block;

  • if the initialisation is a complex operation, then a method with a good name will be best;

  • in doubt, use the method syntax and use the method name to declare not only which variable, but also how you are initializing (i.e. initializeValueWithRandomNumber() );

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692023

The static block would be necessary (or at least useful) if two different variables are interdependant and can't be initialized independently.

Suppose you need to read two values from a file, for example. You could store both values in an additional object. But if you really want two constants, a static block is useful.

Upvotes: 3

Related Questions