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.
If we make i as static final then we must assign value to i with the delcaration.
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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Static and non static blank final variables in Java
- Understanding storage of static methods and static variables in Java
- Difference between static and non-static variables in Java
- Final static variable in Java
- final variables in Java
- Final local variables in Java
- Assigning long values carefully in Java to avoid overflow
- Static Variables in Java with Examples
- Are static local variables allowed in Java?
- Output of Java Programs | Set 45 (static and instance variables)
- Unreachable statement using final and non-final variable in Java
- Understanding "static" in "public static void main" in Java
- Why non-static variable cannot be referenced from a static method in Java
- Difference between static and non-static method in Java
- Final arrays in Java
- final vs Immutability in Java
- Blank Final in Java
- Using final with Inheritance in Java
- final keyword in java
- final, finally and finalize in Java
Improved By : karthikthamilarasan