Instance variable as final in Java

Java Programming Java 8Object Oriented Programming

final is a non-access modifier for Java elements. The final modifier is used for finalizing the implementations of classes, methods, and variables. A final instance variable can be explicitly initialized only once.

A final instance variable should be initialized at one of the following occasions −

  • At time of declaration.

  • In constructor.

  • In instance block.

Compiler will throw error, it a final variable is not initialized at all using any of the above methods. Following examples showcases example of instance variables as final.

Example

 Live Demo

public class Tester{
   final int A = 1;
   final int B;{
      B = 2;
   }
   final int C;
   Tester(){
      C = 3;
   }

   public static void main(String[] args) {
      Tester t = new Tester();
      System.out.println("A = " + t.A + ", B = " + t.B + ", C = " + t.C);
   }
}

Output

A = 1, B = 2, C = 3
raja
Published on 19-Sep-2018 08:21:42
Advertisements