Search code examples
javainitializer

When are initializer blocks used in java?


I read that an initializer block is "an unnamed code block that contains th code that initializes the class?

For example :

class A {
  final int x;
  final int y;
  final String n;

{ 
    x = 10;
    y = 20;
}

public A(String name ) {

/* etc... etc */

I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?

thanks


Solution

  • A common use for this is the static initializer block:

    class A {
        static boolean verbose;
        final int x;
        final int y;
        final String n;
    
    static { 
        verbose = doSomethingToGetThisValue();
    }
    
    public A(String name ) {
    
    /* etc... etc */
    

    This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).

    See also this SO answer.