Skip to content
C

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

java
final dataType CONSTANT_NAME = value;

5. Example Program

java
public 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.0

6. Key Points to Remember

  • Constants use the final keyword and, by convention, are named in UPPERCASE.
  • Trying to reassign a final variable causes a compile-time error.
  • Constants make code more readable by giving meaning to fixed values.

Mock Test

  • Constants - Quick Test

    10 questions on the final keyword and using fixed values in Java.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems