Playing around with Initialization of Final Variables

Final variables declared inside class, it can be divided into final variable, or static final variable.

These two types have two different initialization method.

For final variable, the first type, we should declare it in constructor, or initializer block.

For static final variable, the second type, we should declare it in static initializer block.

These two methods unless you initialized them when you declare. I mean final int a = 3; you directly assign a number 3 to it.

Now, I am playing around with initialization of final variables, as the below is my coding, you all can refer it…

public class FinalStuff {
    final int a;

    static final int d;

    // use static initializer block to initialize static final int
    static {
        c = 3;
        d = 4;
        System.out.println("I am static initializer block");
    }
    static final int c;

    {
            a = 1 + this.b;
            b = 2 + this.d;
            System.out.println("I am initializer block");
    }
    final int b;
    // use initializer block OR FinalStuff constructor to initialize final int
    public FinalStuff() {
        //a = 1;
        //b = 2;
        System.out.println("I am constructor");
    }

    public static void main(String args[]) {
        FinalStuff f = new FinalStuff();
        System.out.println(f.a + " " + f.b + " " + f.c + " " + f.d);
    }
}

 

Java Final, Static, Initializer Block

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.