Defining Constant

Java 8
final double PI = 3.14;

final double E = Math.pow(
    Math.pow(PI,4) + Math.pow(PI,5), 1.0/6);

final declares a read-only block-scoped reference to a value.

In Java, constant values can be assigned one time, either by initializing in declaration or assignment later, but once it is set, it cannot change.

While the reference itself is immutable, if constant is pointing to an array or an object, elements inside them can change.

final int[] BITS = new int[]{0, 1};
BITS = new int[]{0, 0};  // error
BITS[0] = 1;    // BITS -> [1, 1]

Defining Constants in one line

Java 8
final double PI = 3.14, E = 2.71;

You can define multiple constants in one statement.

Here, we are creating constants PI and E.


Getting Constant value

Java 8
final double PI = 3.14;

int r = 2;
double area = r * r * PI;  // area -> 12.56

To get the value of a Constant, you can simply use its name.