Home > Tech > Java – Final vs. Static Variable

Java – Final vs. Static Variable

November 13th, 2008 x=vv= Leave a comment Go to comments

The “static” and “final” modifier in Java are somehow confusing, especially when they interact. Here is a good explanation on how to understand these two modifiers:

You DO NOT have to assign a value to a final variable when you declare it. The “final” keyword just means that you can (and must) assign its value exactly once. Where you are allowed to assign the value depends on if it is static or not (as well as its access modifier).

private final int j;
The value MUST be assigned ONCE, either here in the declaration or in each constructor. It is NOT automatically assigned a value of 0 (zero). Also, since it is not static, there is a distinct value for each instance object, so it makes sense that it must be assigned in the constructor.

private static int k;
The value may be assigned from anywhere in this class. Since it is not final, the value may be assigned any number of times, but since it is static, this value is stored at the class-level and universally available to all instances. If left unassigned, it is assumed to be 0 (zero).

private static final int i;
The value MUST be assigned ONCE, either here in the declaration or in a “static” class-level block. It is NOT automatically assigned a value of 0 (zero).

So, to review:
“final”: per-instance value, must be assigned once per instance.
“final” + “static”: per-class value, must be assigned once per class.
“static”: per-class value, can be assigned any number of times per class.
[neither modifier]: per-instance value, can be assigned any number of times per instance.

Before Java can create an instance of a class, it must first load and initialize that class. One step of class initialization is assigning values to all its static fields. If they’re static AND final, those values can’t change once they’re assigned.

  1. November 29th, 2008 at 15:35 | #1

    Good explanation. Appreciate it.

  2. March 8th, 2009 at 21:24 | #2

    Very good explanation.

  3. srikanth
    March 17th, 2009 at 15:22 | #3

    thank you very much….confused lot of times abt this….
    but ur explaination cleared every thing….

  4. Joy
    June 19th, 2009 at 04:09 | #4

    Thanks for the explanation – very concise and told me exactly what I wanted to know.

  1. No trackbacks yet.