
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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 );
Advertisements