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.
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.
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);
}
}
Old Tax Rate: 0.03
New Tax Rate: 0.09
There are two advantages to using constants:
Note: also read about the Variables in Java
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…