- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
- Related Articles
- Final static variables in Java
- Static and non static blank final variables in Java
- Assigning Values to Variables in Python
- What is blank final variable? What are Static blank final variables in Java?
- Assigning long values carefully in java to avoid overflow\n
- Interface variables are static and final by default in Java, Why?
- Are static local variables allowed in Java?\n
- final variables in Java
- Static variables in Java
- Default values of static variables in C
- Initializer for final static field in Java
- Difference Between Static and Final in Java
- Class and Static Variables in Java
- Why variables are declared final in Java
- What is static blank final variable in Java?
