How to declare constants in java

A constant is a identifier whose value cannot be changed once it is defined. Java does not have built-in support for constants.

In Java, a variable can be declared as constant using static and final modifiers. Constants are used when the identifier value should not be changed.

The syntax is

static final datatype identifier_name = value;

The static modifier is used to manage memory and to make the variable available without creating an instance of the class in which it is defined. The final modifier makes the variable unchangeable.

If a variable is declared as only static then all the objects of the same class will be able to access the variable and change its value. If a variable is declared as final and non-static, then multiple instances of the same constant value will be created for every different object and that is not efficient.

Hence both static and final are used to declare a variable as a constant.

It is convenient to capitalize the name of the variable which is to be declared as constant.

public class Example {
  // declaring constant variable
  static final int MIN_VALUE = 10;
  public static void main(String[] args) {
    System.out.println("Constant variable = " + MIN_VALUE);
  }
}

The output is

Constant variable = 10

We cannot change the constant value throughout the program. If the user attempts to change the value of the constant inside the program, an error is encountered.

public class Example {
  static final int MIN_VALUE = 10;
  public static void main(String[] args) {
    // trying to change value of MIN_VALUE
    MIN_VALUE = 15;
    System.out.println("Constant variable = " + MIN_VALUE);
  }
}

The output is

java-constant-change-value

0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions