Can we declare final variables without initialization in java?


In Java, final is the access modifier which can be used with a filed class and a method.

  • When a method if final it cannot be overridden.
  • When a variable is final its value cannot be modified further.
  • When a class is final it cannot be extended.

Declaring final variable without initialization

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values.

Therefore, it is mandatory to initialize final variables once you declare them.

Still, if you try to declare final variables without initialization that will generate a compilation error saying "variable variable_name not initialized in the default constructor"

Example

In the following Java program, the class Student contains two final variables name and age and they have not been initialized.

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public void display(){
      System.out.println("Name of the Student: "+this.name);
      System.out.println("Age of the Student: "+this.age);
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compile time error

On compiling, this program generates the following error.

Output

Student.java:3: error: variable name not initialized in the default constructor
private final String name;
^
Student.java:4: error: variable age not initialized in the default constructor
private final int age;
^
2 errors

To resolve this, you need to initialize the declared final variables as −

Example

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public Student(){
      this.name = "Raju";
         this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Output

Name of the Student: Raju
Age of the Student: 20

Updated on: 29-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements