Wednesday, January 28, 2026
HomeLanguagesJavaAssigning values to static final variables in Java

Assigning values to static final variables in Java

Assigning values to static final variables in Java: 
In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.
For example, following program works fine. 
 

Java




class Test {
 
    // i could be assigned a value here
    // or constructor or init block also.
    final int i;
    Test()
    {
        i = 10;
    }
 
    // other stuff in the class
}


If we make i as static final then we must assign value to i with the declaration. 
 

Java




class Test {
 
    // Since i is static final,
    // it must be assigned value here
    // or inside static block .
    static final int i;
    static
    {
        i = 10;
    }
 
    // other stuff in the class
}


Such behavior is obvious as static variables are shared among all the objects of a class; creating a new object would change the same static variable which is not allowed if the static variable is final.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32475 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6848 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6915 POSTS0 COMMENTS