java

Java Constant


What is Constant?

 

  • Constant is a variable whose value should not be changed once it assigned.
  • The 'final' keyword is used to declare a constant.

 

Example

 

static final float PI = 3.14;

 

Why static and final?

 

  • When a variable is declared as ‘final’ it means it's value can't be changed once assigned. It become a constant.
  • A final variable can be assigned a value only once, either during its declaration or in a constructor.
  • Combination of ‘static’ and 'final' means the variable is a constant associated with the class, and its value is shared among all instances of that class.

 

Note:  Constant variable names in Java are often written in uppercase letters with underscores.

 

public class Example {
    // Constant variable
    public static final int MY_CONSTANT = 10;

    public static void main(String[] args) {
        // Accessing the constant
        System.out.println("Constant value: " + Example.MY_CONSTANT);
    }
}