Final in Java

Final in Java

‘final’ is a keyword in Java used in several aspects and contexts. The keyword ‘final’ is mainly used as a non-access modifier and can only be associated to a variable, a method, or a class. When used with each of these, the final keyword gives different meanings to them as follows:

  • A variable defined as final is treated as a constant variable that cannot be modified throughout the code.
  • A method that is defined as final is a method that cannot be overridden. Therefore, the final keyword prevents overriding a method.
  • Final classes are those classes that cannot be inherited.

Final Variable

As mentioned before, when you define a variable to be final, it acts in a way such that the variable is treated to be a constant and its value cannot be modified. Therefore, all final variables are normally initialized and set right at the beginning of your code. In a situation where the final variable works as a reference, the variable cannot be re-bound to such that it refers to another object. The only change that is allowed is the internal state of the object. This means that if dealing with an array or collection that is declared to be final, elements can be added or removed from them. As a Java convention like many other, all final variable names are written in capital letters and underscore is used to separate words.

Example

// a final variable

final int THRESHOLD = 5;

// a blank final variable

final int THRESHOLD;

// a final static variable PI

static final double PI = 3.14159

// a blank final static variable

static final double PI;

 

 

Initializing a final variable

As final variables are treated as constant, therefore these variables have to initialized as a mandate otherwise the compiler will treat this as an error. You can either use an initializer or an assignment statement to initialize a final variable but such variables can only be initialized only once. The following three ways can be used to initialize a final variable:

  1. The most common approach is to initialize the final variable after declaring it right at the front. A final variable is called blank final variable if it is not initialized while declaration.
  2. A final variable can also be initialized using an instance-initializer block or inside a constructor. If there are more than one constructors in your program, as a mandate, the final variable needs to be initialized in all of them otherwise it will lead to a compile time error.
  3. A static block can also be used to initialize a blank final static variable.

Example

Sample Code to see how a final variable can be initialized

class Demo
{
final int THRESHOLD = 5;

final int CAPACITY;

final int MINIMUM;

static final double PI = 3.121;

static final double EULERCONSTANT;

//This is the initializer block for initializing the final variable CAPACITY

{
CAPACITY = 25;
}

static
{
EULERCONSTANT = 2.3;
}

public Demo()
{
MINIMUM = -1;
}
}

 

When to use the final variable?

As the name suggests, final variables are variables whose values cannot be changed once set throughout the scope of the program. This differs from normal variables in this only aspect where normal variables can be overwritten with any value in the program. Therefore, final variables should be very carefully chosen such that it will remain constant throughout the program.

Reference Final Variable

Reference Final Variables are final variables that work as references to an object. As a simple example, the following is a reference variable:

final StringBuffer sb;

Although final variables cannot be reassigned, if dealing with a reference final variable, the internal state of the object pointed by that reference variable can be changed and the following feature is not equivalent to re-assignment. This following property of final is called non-transitivity. The following code will explain the concept of state of an object:

class Demo
{
public static void main (String args [])
{
final StringBuilder sb = new StringBuilder (“Hello World”);

System.out.println (sb);

sb.append (“Java”);

System.out.println (sb);
}
}

 

OUTPUT

Hello World
Hello World Java

Since Arrays are objects in Java, therefore arrays can also be treated as final elements. Therefore, any array that is declared as final is called a final array.

Properties of the final keyword

A few properties of the final keyword are discussed below:

  1. s mentioned before, variables declared final cannot be reassigned throughout the scope of the program. A compile time error is thrown if a reassignment is made in the code.
    class Demo
    {
    static final int CAPACITY = 4;
    
    public static void main (String args [])
    {
    CAPACITY = 5;
    }
    }

    OUTPUT
    Compiler Error: cannot assign a value to final variable CAPACITY

  2. While final variables declared outside methods are called global final variables, final variables declared inside methods, constructors, or blocks are called local final variables. Such variables must be initialized inside the scope it is applicable in. The following code shows a local final variable put to us:
    class Demo
    {
    public static void main (String args [])
    {
    final int I;
    I = 20;
    out.println (i);
    }
    }

     

    OUTPUT
    20

  3. Although C++ constant variables work in a similar fashion to Java final variables, the only difference lies in the fact C++ variables need to initialized in the same declaration line. However, Java final variables can be declared and initialized in phases However, once a value has been assigned to the variable, it cannot be reassigned.
  4. A final variable can be associated with a for each loop. It is a legal execution in Java.
    class Demo
    {
    public static void main (String args [])
    {
    int arr [] = {1, 2, 3};
    for (final int i : arr)
    out.println (i + “ ”);
    }
    }

    OUTPUT
    1 2 3

    In this case, every time the loop control variable goes out of scope with every iteration, a re-declaration of the i variable takes place. Therefore, even though the LCV is a final variable, it represents multiple variables in the process

Final Classes

Classes that are declared with the keyword final are known as final classes. Such classes cannot ne inherited (extended). Final classes are often required in the following two cases:

  1. As final classes cannot be inherited or extended, classes are intentionally defined as final to prevent inheritance. All WrapperClasses like Integrer, Float, etc, are final classes and cannot be extended
    final class A
    {
    //Methods and fields
    }
    
    class B extends A
    {
    //compile-time error as A is a final class and cannot be extended
    }
  2. Final classes are also used to create an immutable class like the String class. An immutable class needs to be a final class.

Final Methods

When methods are declared with the final keyword, the methods become final methods and such methods cannot be overridden. The Object class uses this feature quite often as a lot of its methods are defined as final. After defining methods to be final, the same implementation has to be continued throughout all the derived classes. Follow the code below to understand final methods better:

class A
{
final void m1 ()
{
System.out.println (“This is a final Method”);
}
}

class B extends A
{
void m1()
{
//Cannot be overridden as the method is declared to be final.
System.out.println (“Illegal!”);
}
}

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.