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

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