Why variables are declared final in Java


A variable cannot be modified after it is declared as final. In other words, a final variable is constant. So, a final variable must be initialized and an error occurs if there is any attempt to change the value.

A program that demonstrates a final variable in Java is given as follows −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      final double PI = 3.141592653589793;
      System.out.println("The value of pi is: " + PI);
   }
}

Output

The value of pi is: 3.141592653589793

Now let us understand the above program.

In the main() method in class Demo, the final variable PI is defined and initialized. It stores the value of pi. Then this is printed. A code snippet which demonstrates this is as follows −

final double PI = 3.141592653589793;
System.out.println("The value of pi is: " + PI );

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jun-2020

823 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements