Java Constant

As the name suggests, a constant is an entity in programming that is immutable. In other words, the value that cannot be changed. Usually, to accomplish this, the variable is declared using the final keyword. Constants are frequently used to represent stable values, like mathematical constants, configuration settings, or flag values, that do not change while a program is running. A variable's value is guaranteed to stay constant and unintentionally changed if it is declared as a constant. For easier reading, constants are usually defined in uppercase and underscores between words. Furthermore, variables can be specified either at the instance level (non-static constants) or at the class level (static constants).

What is constant?

Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final.

How to declare constant in Java?

In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.

Static and Final Modifiers

  • The purpose to use the static modifier is to manage the memory.
  • It also allows the variable to be available without loading any instance of the class in which it is defined.
  • The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows:

For example, price is a variable that we want to make constant.

Where static and final are the non-access modifiers. The double is the data type and PRICE is the identifier name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available without an instance of its defining class being loaded and the final modifier makes the variable fixed.

Here a question arises that why we use both static and final modifiers to declare a constant?

If we declare a variable as static, all the objects of the class (in which constant is defined) will be able to access the variable and can be changed its value. To overcome this problem, we use the final modifier with a static modifier.

When the variable defined as final, the multiple instances of the same constant value will be created for every different object which is not desirable.

When we use static and final modifiers together, the variable remains static and can be initialized once. Therefore, to declare a variable as constant, we use both static and final modifiers. It shares a common memory location for all objects of its containing class.

Why we use constants?

The use of constants in programming makes the program easy and understandable which can be easily understood by others. It also affects the performance because a constant variable is cached by both JVM and the application.

Points to Remember:

  • Write the identifier name in capital letters that we want to declare as constant. For example, MAX=12.
  • If we use the private access-specifier before the constant name, the value of the constant cannot be changed in that particular class.
  • If we use the public access-specifier before the constant name, the value of the constant can be changed in the program.

Let's see some examples in which we have used constants.

Example 1: Declaring Constant as Private

ConstantExample1.java

Output:

Java Constant

Explanation

A class with the main() method to determine the total cost based on a fixed price per unit is defined by the Java program ConstantExample1. To guarantee its immutability, it declares a constant PRICE with the value 234.90 by employing the last keyword.

The application asks the user to enter the number of units used, uses a scanner to read the input, multiplies the price per unit (PRICE) by the quantity of units used to determine the total bill, and then shows the total amount that needs to be deposited. It illustrates how to describe a fixed value that doesn't change during program execution in Java using a constant.

Example 2:

ConstantExample2.java

Output:

Java Constant

Explanation

In the above program, we have defined two classes named ConstantExample2 and ConstantExample. The PRICE constant that has the value 2999, is declared in the ConstantExample2 class. The main() method of this class uses this constant to print the previous price of iron. The showPrice() function of the ConstantExample class is also called upon the creation of an instance of the class. Another constant, PRICE, is declared in the ConstantExample class with a value of 3599. The showPrice() method uses this constant to output the current iron price.

Example 3: Declaring Constant as Public

In the following example, we have declared constant PI as public. Inside the main() method, we have assigned 3.15 in the constant PI. After that, we have invoked the printValue() method. When we execute the program, it shows an error cannot assign a value to the final variable PI.

ConstantExample3.java

Output:

Java Constant

Explanation

ConstantExample3, a Java program, defines a class that has two methods: printValue() and main. To assure its immutability, it uses the final keyword to declare a constant PI with the value 3.14. To print the initial value of PI, the printValue() method is called in the main method.

It then tries to give the constant PI a new value (3.15), which is prohibited because it has been declared final. It would give rise to an error in compilation. In order to emphasize the immutability of constants in Java, the printValue() method is called once more to show that the value of PI cannot be altered.

Using Enumeration (enum) as Constant

  • It is the same as the final variables.
  • It is a list of constants.
  • Java provides the enum keyword to define the enumeration.
  • It defines a class type by making enumeration in the class that may contain instance variables, methods, and constructors.

Example of Enumeration

Output:

Java Constant

Explanation

The Java program EnumExample defines a class with a nested enum named Color. The predefined colors Red, Green, Blue, Purple, Black, White, Pink, and Grey are represented by this enum.

The values() function is used in the main() method's for-each loop to iterate over the Colour enum's values and print each color to the console. It shows how to use an extended for loop to iterate over the elements of an enum and how to use enums in Java to express a fixed collection of constants.

Conclusion

To sum up, constants are essential to Java programming since they provide immutable values that do not change while a program runs. Variables can be declared as constants, guaranteeing that their values cannot be changed once assigned by combining the final and static modifiers.

It increases the readability of the code, preserves program integrity, and boosts performance because the application and JVM both cache constant variables. Constants also follow the naming guidelines for Java variables that usually include uppercase letters and underscores for easier reading.

Additionally, enum give a structured method of representing fixed values in programs by making it easy to establish a group of linked constants. Java programmers can produce codebases that are more reliable and manageable by comprehending and making good use of constants.


Next TopicJava Tokens