Java Constants Initialization Guide
In Java, constants can be initialized in the following ways:
- Assign value directly
public class Constants {
public static final int MAX_VALUE = 100;
public static final String MESSAGE = "Hello, World!";
}
- Static initialization block:
public class Constants {
public static final int MAX_VALUE;
public static final String MESSAGE;
static {
MAX_VALUE = 100;
MESSAGE = "Hello, World!";
}
}
Within a static initializer block, more complex initialization operations can be carried out, such as calculations, invoking other methods, and so on.
Once constants are initialized in Java, their values cannot be changed during runtime regardless of the method used for initialization.