java 010

Опубликовано: 16 Июль 2026
на канале: Ruqy STA & IT
230
37

constant is a variable whose value cannot change once it has been assigned. Java doesn't have built-in support for constants.

A constant can make our program more easily read and understood by others. In addition, a constant is cached by the JVM as well as our application, so using a constant can improve performance.

To define a variable as a constant, we just need to add the keyword “final” in front of the variable declaration.

Syntax
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. It is not mandatory that we need to assign values of constants during initialization itself.

In the below example, we can define the primitive data type (byte, short, int, long, float, double, boolean and char) variables as constants by just adding the keyword “final” when we declare the variable.