Java - final Instance Variables

Introduction

A final instance variable does not change after the object is created.

A blank final instance variable must be initialized when an object is created.

A blank final instance variable must be initialized once and only once when any of the constructors of the class is invoked.

Example

Declare and initialize instance final variable

x has been initialized at the time of its declaration and its value cannot be changed afterwards.

public class Test {
    private final int x = 10;
}

The following code shows how to initialize final instance variable in the constructor.

public class Main {
  final int i;
  public Main(){
    i=0;
  }

}

Related Topic