Home   |   About   |   Terms   |   Contact    
Read & Learn
 

How to declare constant variables in Java?

Java

☯ All Java Articles     ☯ All Articles


A new product.






Popular Google Pages:




This article is regarding How to declare constant variables in Java?
Last updated on: .



◕ How to declare constant variables in Java?

By using the final keyword we declare one constant in Java.

Example:
final int MONTH_PER_YEAR = 12; // Constant values

final double HOUR_PER_DAY = 24.0; // another constant

The final keyword indicates that the value of this variable is final and must not be changed.
We generally use the uppercase letters to declare a constant.
It makes it easy to read which variables are declared as constant.
Any variable we declare as final must have an initial value. Because we can not specify it later.



◕ Why declare a constant variable in Java is useful?

Let the above variable declaration

final int MONTH_PER_YEAR = 12; // Constant values

final double HOUR_PER_DAY = 24.0; // another constant

We know 12 months are there in a Year and 24 hours are there in a day.
If we use 12 in our program it could mean anything. 24 could mean two feet also in Inch.
But if we store the value 12 in the final variable MONTH_PER_YEAR and use the variable name in the program it clears everything.
Similarly if we store the value 24 in the final variable HOUR_PER_DAY and use the variable name in the program it clears all confusion.
This makes our program very easy to read and understand.



Related Java articles:
What is Java? Where we can apply Java?
Why Java is a Machine Independent Program? What is Machine Independent Program?
Root Directory of Java
How to Compile and run a Java Program?
What is .class file in Java?
What is variable in a program?
What is identifier in Java?
Integer data types in Java?
What is Primitive Types in Java?
How to declare constant variables in Java?
Why should we declare the initial value of a variable in Java?
Use of Underscores to write an integer in Java





Popular Google Pages:





Top of the page

Amazon & Flipkart Special Products

   


Top of the page