Blank final in Java

Object Oriented ProgrammingJava Programming Java8Java Technologies

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
raja
Published on 20-Jul-2018 12:03:58
Advertisements