Java Reference
In-Depth Information
final int multiplier; // A blank final variable
/* Do something here... */
// Set the value of multiplier first time
multiplier = 3;
// Ok to read the multiplier variable
int value = 100 * multiplier;
Let's go through examples of each type of variable and how to declare them
final
.
final Local Variables
You can declare a local variable
final
. If you declare a local variable as a blank
final
variable, you must initialize
it before using. You will receive a compilation time error if you try to change the value of the
final
local variable
the second time. The following snippet of code uses
final
and blank
final
local variables in the
test()
method.
Comments in the code explain what you can do with
final
variables in the code.
public static void test() {
int x = 4; // 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 = 87;
/* Can read z now. Cannot change z here onwards */
x = x + y + z;
/* Perform other logic here... */
}
final Parameters
You can also declare a formal parameter
final
. A formal parameter is initialized automatically with the value of the
actual parameter when the method or the constructor is invoked. Therefore, you cannot change the value of a
final
formal parameter inside the method's or the constructor's body. The following snippet of code shows the
final
formal parameter
x
for the
test2()
method:
public void test2(final int x) {
/* Can read x, but cannot change it */
int y = x = 11;
/* Perform other logic here... */
}