
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why Java Doesn't Allow Initialization of Static Final Variable in a Constructor
If you declare a variable static and final you need to initialize it either at declaration or, in the static block. If you try to initialize it in the constructor, the compiler assumes that you are trying to reassign value to it and generates a compile time error −
Example
class Data { static final int num; Data(int i) { num = i; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
Compile time error
ConstantsExample.java:4: error: cannot assign a value to final variable num num = i; ^ 1 error
To make this program work you need to initialize the final static variable in a static block as −
Example
class Data { static final int num; static { num = 1000; } } public class ConstantsExample { public static void main(String args[]) { System.out.println("value of the constant: "+Data.num); } }
Output
value of the constant: 1000
Advertisements