
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
What is a constant and how to define constants in Java?
Constants in Java
A constant is a variable whose value cannot be changed once it has been initialized. Java doesn't have built-in support for constants. To define a variable as a constant, we just need to add the keyword "final" in front of the variable declaration.
It is not mandatory that we assign values to constants during declaration.
Syntax of Java Constant
final float pi = 3.14f;
The above statement declares the float variable "pi" as a constant with a value of 3.14f. We cannot change the value of "pi" at any point in time in the program. Later, if we try to do that by using a statement like "pi=5.25f", Java will throw errors at compile time itself.
Example: Defining Constants
In the below example, we define the primitive data type (byte, int, double, boolean, and char) variables as constants by just adding the keyword "final" when we declare the variable.
public class ConstantsDemo { public static void main(String args[]) { final byte var1 = 2; final byte var2; var2 = -3; final int var3 = 100; final int var4; var4 = -112; final double var5 = 20000.3223; final double var6; var6 = -11223.222; final boolean var7 = true; final boolean var8; var8 = false; final char var9 = 'e'; final char var10; var10 = 't'; // Displaying values of all variables System.out.println("value of var1 : "+var1); System.out.println("value of var2 : "+var2); System.out.println("value of var3 : "+var3); System.out.println("value of var4 : "+var4); System.out.println("value of var5 : "+var5); System.out.println("value of var6 : "+var6); System.out.println("value of var7 : "+var7); System.out.println("value of var8 : "+var8); System.out.println("value of var9 : "+var9); System.out.println("value of var10 : "+var10); } }
Output
value of var1 : 2 value of var2 : -3 value of var3 : 100 value of var4 : -112 value of var5 : 20000.3223 value of var6 : -11223.222 value of var7 : true value of var8 : false value of var9 : e value of var10 : t
The final Keyword
The final keyword is a non-access modifier and is used with variables, methods, and classes so that they cannot be changed.
Methods that are defined as final cannot be overridden, and classes that are defined as final cannot be inherited. And, the value of final variables, as discussed above, cannot be changed as they become constant.