Java - Class final variable

Syntax

To declare a variable as final, use the final keyword in the variable's declaration.

Example

The following code declares four final variables: YES, NO, MSG, and account:

final int YES = 1;
final int NO = 2;
final String MSG = "message";
final Account account = new Account();

You can set the value of a final variable only once.

Setting the value of a final variable the second time will generate a compilation time error.

final int x = 10;
int y = 101 + x; // Reading x is ok

x = 1;// A compilation time error. 

final variable assignment

There are two ways to initialize a final variable:

  • initialize it at the time of its declaration.
  • defer its initialization until a later time.

Example

The following code shows how to defer final variable initialization until a later time.

final int multiplier; // A blank final variable
// Set the value of multiplier first time
multiplier = 3;

// Ok to read the multiplier variable
int value = 100 * multiplier;

Related Topic