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
[Link]("value of var1 : "+var1);
[Link]("value of var2 : "+var2);
[Link]("value of var3 : "+var3);
[Link]("value of var4 : "+var4);
[Link]("value of var5 : "+var5);
[Link]("value of var6 : "+var6);
[Link]("value of var7 : "+var7);
[Link]("value of var8 : "+var8);
[Link]("value of var9 : "+var9);
[Link]("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