Can a final variable be initialized when an object is created in Java?


Once you declare a variable final, after initializing it, you cannot modify its value further. 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. If not a compile time error will be generated.

Example

 Live Demo

public class FinalExample {
   final int j;
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      System.out.println(obj.j);
   }
}

Compile time error

FinalExample.java:5: error: non-static variable j cannot be referenced from a static context
System.out.println(j);
^
1 error

Initializing the final variable

You can initialize a final variable in 4 ways −

While declaring it.

 Live Demo

public class FinalExample {
   final int j = 100;
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      System.out.println(obj.j);
   }
}

Output

100

Using the final methods.

 Live Demo

import java.util.Scanner;
public class FinalExample {
   final int num = getNum();
   public static final int getNum() {
      System.out.println("Enter the num value");
      return new Scanner(System.in).nextInt();
   }
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      System.out.println(obj.num);
   }
}

Output

Enter the num value
20
20

Using the Constructors

 Live Demo

public class FinalExample {
   final int num;
   public FinalExample(int num) {
      this.num = num;
   }
   public static void main(String args[]){
      FinalExample obj = new FinalExample(20);
      System.out.println(obj.num);
   }
}

Output

20

Using the Instance initialization blocks

 Live Demo

public class FinalExample {
   final int num; {
      num = 500;
   }
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      System.out.println(obj.num);
   }
}

Output

500

Except in the case of final method, if you initialize the final variable in all the other three ways it will be initialized soon you instantiate its class.

Updated on: 11-Oct-2019

770 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements