

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 should a blank final variable be explicitly initialized in all Java constructors?
A final variable which is left without initialization is known as blank final variable.
Generally, we initialize instance variables in the constructor. If we miss out they will be initialized by the constructors by default values. But, the final blank variables will not be initialized with default values. So if you try to use a blank final variable without initializing in the constructor, a compile time error will be generated.
Example
public class Student { public final String name; public void display() { System.out.println("Name of the Student: "+this.name); } public static void main(String args[]) { new Student().display(); } }
Compile time error
On compiling, this program generates the following error.
Student.java:3: error: variable name not initialized in the default constructor private final String name; ^ 1 error
Therefore, it is mandatory to initialize final variables once you declare them. If more than one constructor is provided in the class, you need to initialize the blank final variable in all the constructors.
Example
public class Student { public final String name; public Student() { this.name = "Raju"; } public Student(String name) { this.name = name; } public void display() { System.out.println("Name of the Student: "+this.name); } public static void main(String args[]) { new Student().display(); new Student("Radha").display(); } }
Output
Name of the Student: Raju Name of the Student: Radha
- Related Questions & Answers
- Can a final variable be initialized when an object is created in Java?
- What is blank final variable? What are Static blank final variables in Java?
- What is a blank uninitialized final variable in java?
- What is static blank final variable in Java?
- Can we initialize blank final variable in Java
- What is blank or uninitialized final variable in Java?
- Blank final in Java
- Why a constructor cannot be final in Java?
- Can constructors be marked final, abstract or static in Java?
- Why constructor cannot be final in Java
- Final variable in Java
- final local variable in Java
- What is a final variable in java?
- Get all Constructors in Java
- Static and non static blank final variables in Java
Advertisements