Java by Example: Constants

Java uses the final keyword to denote constant variables. These variables can be of any type.

public class Main

The final keyword declares a constant value.

public static final String S = "constant";
public static void main(String[] args) {
    System.out.println(S);

A final variable can be declared anywhere a regular variable can be declared.

    public static final int N = 500000000;

Final variables must be assigned a value exactly once. This can be done at the time of declaration, in the constructor, or in an instance initializer block for non-static variables.

    final int d;
    { // initializer block
        d = 1000;
    }

A final variable can be used in any context where a regular variable can be used.

    System.out.println(N);
}
$ java Main
constant
500000000

Next example: For.

t