Java - final Local Variables

Introduction

The following code uses final and blank final local variables in the test() method.

public class Main {

  public static void main(String[] args) {
    int x = 0; // A variable
    final int y = 10; // A final variable. Cannot change y here onward
    final int z; // A blank final variable

    // We can read x and y, and modify x
    x = x + y;

    /* We cannot read z here because it is not initialized yet */

    /* Initialize the blank final variable z */
    z = 1;

    /* Can read z now. Cannot change z here onwards */
    x = x + z;
  }
}

Related Topic