简体   繁体   中英

static final variable initialization in java

I have a doubt in static final variable.In the following program:

class StaticPuzzel2 {
    public static void main (String[] args) {
    }
    final static int i;
    static {
            System.out.print ("\n\t"+ StaticPuzzel2.i);
            i = 11;
            System.out.print ("\n\t"+ StaticPuzzel2.i);
            System.out.print ("\n\t"+ i);
    }
}

Even though the final variable has not been initialized it is not throwing error. Why it is so?

I assume you're wondering why it doesn't throw an error when you access it before setting it to 11 . The reason is, that the variable is actually initialized with the default value (zero), and changed at runtime just like any other variable.

When using a static initialization block, the final modifier only makes sure you are assigning a value to the variable only once. What it doesn't do, is making it non-existent before that has happened.

You are initializing static variable in static block. That's why.

Try this: final static int i = 0;

From java specs :

A variable can be declared final. A final variable may only be assigned to once. It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment

So it doesn't actually means that if should be initialized at declaration. But it means that it can only be assigned once and this assignment can be part of declaration or initializer blocks as in your case. This is will give you error now.

You can check this answer for more details. Java - Can final variables be initialized in static initialization block?

Because it has been already initialized in static block. If you comment out that line it will give a compilation error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM