Constants in Java

  • April 27, 2022
  • Java
method overloading and method overriding

In programming, a constant is an immutable entity. To put it another way, the value cannot be altered.

In a program, we often want to give a name to a constant value. For instance, we might have a fixed tax rate of 0.030 for goods and a tax rate of 0.020 for services. These are constants because their value is not going to change when the program is executed. It is convenient to give these constants a name.

We use the static and final modifiers in Java to declare any variable as a constant. Non-access modifiers are another name for it. The identifier name must be in capital letters according to the Java naming convention.

Final and Static Modifiers
  • The static modifier is used to keep track of memory usage.
  • It also makes the variable accessible without requiring the loading of any instances of the class in which it is defined.
  • The final modifier indicates that the variable’s value cannot be changed. The primitive data type becomes immutable or unchangeable as a result of this.

This can be done as follows:

static final double TAXRATE= 0.25;

Note: Why do we use both static and final modifiers to declare a constant in this case?

All objects of the class (in which the constant is defined) will be able to access the variable and change its value if we declare it as static. We use the final modifier in conjunction with a static modifier to solve this problem.

When a variable is declared final, multiple instances of the same constant value are created for each object, which is undesirable.

When we combine the static and final modifiers, the variable stays static and only needs to be initialized once. As a result, we use both the static and final modifiers to declare a variable as a constant. All objects in its containing class share a common memory location.

Example:
 public class ConstantExample2  
{  
private static final double TAXRATE=0.030;  
public static void main(String[] args)  
{  
System.out.println("\nOld Tax Rate: "+TAXRATE);  
ConstantExample obj = new ConstantExample();  
obj.showTax();  
}  
}  
class ConstantExample  
{  
private static final double TAXRATE=0.09;  
void showTax()  
{  
System.out.print("\nNew Tax Rate: "+TAXRATE);  
}  
}  
Output:
Old Tax Rate: 0.03
New Tax Rate: 0.09
Advantages of Constants:

There are two advantages to using constants:

  • They make our program easier to read and check for corrections.
  • If a constant needs to be changed, all we need to do is change the declaration.

Note: also read about the Variables in Java

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *