Blank final in Java


In Java, a final variable can a be assigned only once. It can be assigned during declaration or at a later stage. A final variable if not assigned any value is treated as a blank final variable. Following are the rules governing initialization of a blank final variable.

  • A blank instance level final variable cannot be left uninitialized.

  • The blank Instance level final variable must be initialized in each constructor.

  • The blank Instance level final variable cannot be initialized in class methods.

  • A blank static final variable cannot be left uninitialized.

  • The static final variable must be initialized in a static block.

  • A static final variable cannot be initialized in constructor or class methods.

Example

 Live Demo

public class Tester {
   public final int a;
   public static final int b;

   static {
      b = 2;
   }          

   Tester() {
      this(1);        
   }

   Tester( int a) {
      this.a = a;
   }

   public static void main(String[] args) {

      Tester tester = new Tester();
      System.out.println("a = " + tester.a + ", b = " + b);
   }
}

Output

a = 1, b = 2

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

571 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements