Final (Java) - Final Variables

Final Variables

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases. (Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.)

Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.

Example:

public class Sphere { // pi is a universal constant, about as constant as anything can be. public static final double PI = 3.141592653589793; public final double radius; public final double xpos; public final double ypos; public final double zpos; Sphere(double x, double y, double z, double r) { radius = r; xpos = x; ypos = y; zpos = z; } }

Any attempt to reassign radius, xpos, ypos, or zpos will meet with a compile error. In fact, even if the constructor doesn't set a final variable, attempting to set it outside the constructor will result in a compilation error.

To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one:

public final Position pos;

where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.

Like full immutability, finality of variables has great advantages, especially in optimization. For instance, Sphere will probably have a function returning its volume; knowing that its radius is constant allows us to memoize the computed volume. If we have relatively few Spheres and we need their volumes very often, the performance gain might be substantial. Making the radius of a Sphere final informs developers and compilers that this sort of optimization is possible in all code that uses Spheres.

Read more about this topic:  Final (Java)

Famous quotes containing the words final and/or variables:

    The prologues are over. It is a question, now,
    Of final belief. So, say that final belief
    Must be in a fiction. It is time to choose.
    Wallace Stevens (1879–1955)

    The variables are surprisingly few.... One can whip or be whipped; one can eat excrement or quaff urine; mouth and private part can be meet in this or that commerce. After which there is the gray of morning and the sour knowledge that things have remained fairly generally the same since man first met goat and woman.
    George Steiner (b. 1929)