How many ways are there to initialize a final variable 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.

Initializing a final variable

Once you declare a final variable, it is a must to initialize it. You can initialize the final instance variable −

  • At the time of declaration as.
public final String name = "Raju";
public final int age = 20;
  • Within an instance (non-static) block.
{
   this.name = "Raju";
   this.age = 20;
}
  • Within a default constructor.
public final String name;
public final int age;
public Student(){
   this.name = "Raju";
   this.age = 20;
}

Note − If you try to initialize the final instance variable elsewhere, a compile-time error will be generated.

Example1: At the time of declaration

In the following Java program, the class Student contains two final variables − name, age and, we are initializing them at the time of declaration −

 Live Demo

public class Student {
   public final String name = "Raju";
   public final int 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

Example2: within an instance block

In the following Java program, the class Student contains two final variables− name, age and, we are initializing them within an instance block −

 Live Demo

public class Student {
   public final String name;
   public final int age; {
      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

Example3: within the default constructor

In the following Java program, the class Student contains two final variables − name, age and, we are initializing them within a default constructor −

 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

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements