
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
Assigning Values to Static Final Variables in Java
In java, a non-static final variable can be assigned a value at two places.
At the time of declaration.
In constructor.
Example
public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } }
Output
1, 2
But in case of being static final, a variable cannot be assigned at the constructor. The compiler will throw a compilation error. A static final variable is required to be assigned in a static block or at time of declaration. So a static final variable can be assigned a value at the following two places.
At the time of declaration.
In static block.
Example
public class Tester { final int A; //Scenario 1: assignment at time of declaration final int B = 2; public Tester() { //Scenario 2: assignment in constructor A = 1; } public void display() { System.out.println(A + ", " + B); } public static void main(String[] args) { Tester tester = new Tester(); tester.display(); } }
Output
1, 2
The reason behind this behavior of the static final variable is simple. A static final is common across the objects and if it is allowed to be assigned in the constructor, then during the creation of an object, this variable is getting changed per object and thus is not assigned once.