Final in Java


Final in Java can refer to variables, methods and classes. The final keyword is used in several contexts to define an entity that can only be assigned once. Once a final variable has been assigned, it always contains the same value.

There are three simple rules :

  • Final variable cannot be reassigned
  • Final method cannot be overridden
  • Final class cannot be extended

The program demonstrates the usage of final keyword with instance variables.

  • In the class Test, there are three final variables - MIN, NORMAL, and MAX. MIN is initialized to a constant value of 1, which means it cannot be modified further. NORMAL and MAX are not initialized in the class, but they are initialized in the constructor of the class. Once initialized, their values cannot be changed.
  • In the constructor of the class, the NORMAL variable is initialized with the value passed as a parameter to the constructor, and the MAX variable is initialized to a constant value of 100.
  • The display() method is used to print the values of all three variables. When the object of the Test class is created, it will initialize NORMAL and MAX variables in the constructor, and then display() method will print the values of all three variables.
  • This program demonstrates the use of final keyword with variables, where once assigned a value, its value cannot be changed. It is useful in situations where the values are not meant to be changed, such as constants.

Source Code

//Final Variables in Java
class Test
{
    final int MIN=1;
    final int NORMAL;
    final int MAX;
 
    Test(int normal) {
        NORMAL = normal;
        MAX =100;
    }
    void display()
    {
        System.out.println("MIN    : "+MIN);
        System.out.println("NORMAL : "+NORMAL);
        System.out.println("MAX    : "+MAX);
    }
}
public class finalTest {
    public static void main(String args[])
    {
        Test o =new Test(50);
        o.display();
    }
}
 

Output

MIN    : 1
NORMAL : 50
MAX    : 100
To download raw file Click Here

Basic Programs