
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Why Java wouldn'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
- Related Articles
- Why final variable doesn't require initialization in main method in java?
- Why we can't initialize static final variable in try/catch block in java?
- Why a constructor cannot be final in Java?
- What is static blank final variable in Java?
- Why interfaces don't have static initialization block when it can have static methods alone in java?
- Why constructor cannot be final in Java
- A static initialization block in Java
- What is blank final variable? What are Static blank final variables in Java?
- A non-static initialization block in Java
- Final variable in Java
- Final static variables in Java
- Initialization of local variable in a conditional block in Java
- Can a constructor be made final in Java?
- Interface variables are static and final by default in Java, Why?
- Why can't static method be abstract in Java?

Advertisements