Where can final variables be initialized?

There are three forms of final variables: class final variables, instance final variables, and local final variables. There is no requirement to initialize a final variable at declaration but it must initialize before using it.

You can only initialize a final variable once.

* For class final variables, the variables can be initialized in either the declaration or static initializer:

class Program {
static final int i1 = 10;
static final int i2;
static {
i2 = 10;
}
}

* For instance final variables, the variables can be initialized in the declaration, instance initializer, or constructor:

class Program {
final int i1 = 10;
final int i2;
final int i3;
{
i2 = 10;
}

Program() {
i3 = 10;
}
}

* For local final variables, the variables can be initlialized in the declaration or any place after its declaration. The local final variables must be initializd before they are used.

class Program {
void method() {
final int i1 = 10;
final int i2;
System.out.println(i1);
i2 = 10;
System.out.println(i2);
return ;
}
}

1 comment:

  1. hey man thanks for sharing this. I have also shared my thoughts on initializing final variables in java. do let me know how do you like it?

    ReplyDelete