- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 );
- Related Articles
- Why are classes sometimes declared final in Java?
- Interface variables are static and final by default in Java, Why?
- final variables in Java
- Final static variables in Java
- What is blank final variable? What are Static blank final variables in Java?
- Assigning values to static final variables in java
- Difference between constants and final variables in Java?
- Why can't variables be declared in a switch statement in C/C++?
- Final variables in C#
- Can we declare final variables without initialization in java?
- Static and non static blank final variables in Java
- Why Final Class used in Java?
- Effectively final variables in try-with-resources in Java 9?
- Final local variables in C#
- Why constructor cannot be final in Java

Advertisements