In Java, symbolic constants are fixed values represented by meaningful names, rather than hard-coded values, which improves code readability and reliability. Java commonly uses final variables and enums to define symbolic constants. It's of various uses:
- Makes programs easier to maintain
- Prevents accidental modification of values
- Eliminates magic numbers
- Enhances consistency across the application
public class GFG {
static final int MAX_AGE = 60;
public static void main(String[] args)
{
System.out.println("Maximum allowed age is: "
+ MAX_AGE);
}
}
Output
Maximum allowed age is: 60
Explanation:
- MAX_AGE is declared as a symbolic constant using static final
- final ensures the value cannot be modified
- static allows access without creating an object
- Using a meaningful name improves code readability and maintenance
Symbolic Constants Using the final Keyword
In Java, a variable declared with the final keyword becomes a constant, meaning its value cannot be changed once assigned.
Syntax:
final dataType CONSTANT_NAME = value;
Using static final for Class-Level Constants
The combination of static and final is commonly used to define class-level symbolic constants.
class GFG {
public static final double PI = 3.14159;
public static void main(String[] args) {
System.out.println("Value of PI: " + PI);
}
}
Output
Value of PI: 3.14159
Explanation:
- static ensures a single shared copy
- final prevents reassignment
- Constants can be accessed using the class name
Symbolic Constants Using enum
For a fixed set of related constants, Java provides the enum type. Enums are type-safe than final variables.
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}
class GFG {
public static void main(String[] args) {
Day today = Day.MONDAY;
System.out.println(today);
}
}
Output
MONDAY
Explanation: Enums represent a predefined set of constants and provide better compile-time safety.
Naming Conventions for Symbolic Constants
Symbolic constants should be written in uppercase letters, with multiple words separated by underscores (_). They should be declared as static final to ensure immutability and class-level access.
public class GFG {
// Symbolic constant
public static final int MAX_AGE = 60;
public static void main(String[] args)
{
int userAge = 45;
if (userAge <= MAX_AGE) {
System.out.println("User is eligible.");
}
else {
System.out.println("User is not eligible.");
}
}
}
Output
User is eligible.
Explanation:
- MAX_AGE is a symbolic constant declared using public static final
- Its value cannot be changed after initialization
- The constant is accessed directly using the class name
- Replacing hard-coded values improves clarity and maintainability
final vs enum
Feature | final Constant | enum |
|---|---|---|
Type Safety | Limited | High |
Use Case | Single fixed value | Fixed set of related values |
Extensibility | Not extensible | Can have methods |
Readability | Good | Excellent |