Constants
A constant is a value that, once assigned, cannot be changed during the program's execution. In Java, you create a constant using the final keyword along with a variable declaration.
1. What is a Constant?
A constant is a value that, once assigned, cannot be changed during the program's execution. In Java, you create a constant using the final keyword along with a variable declaration.
2. Why is it used?
Constants protect important fixed values, like a tax rate or the number of days in a week, from being accidentally changed somewhere else in the code. This makes programs safer and easier to maintain.
3. Real-Life Example
Think of your date of birth. It is a fixed fact that never changes no matter what happens in your life afterward. A constant in Java behaves the same way — fixed once, and never modified again.
4. Syntax
javafinal dataType CONSTANT_NAME = value;
5. Example Program
javapublic class ConstantDemo { public static void main(String[] args) { final double TAX_RATE = 0.18; double price = 1000; double finalPrice = price + (price * TAX_RATE); System.out.println("Final Price: " + finalPrice); } }
Output:
Final Price: 1180.06. Key Points to Remember
- Constants use the
finalkeyword and, by convention, are named in UPPERCASE. - Trying to reassign a
finalvariable causes a compile-time error. - Constants make code more readable by giving meaning to fixed values.