Fundamentals · Easy · Free
What are literals, constants, and magic numbers? Why avoid magic numbers?
FresherFundamentalsProgramming Fundamentals
Literals, constants, magic numbers
A literal is a value written directly in code (42, "OK"). A constant names that value (MAX_RETRIES = 3). A magic number is an unexplained literal scattered in logic—it hides intent and makes bugs when the value changes.
- Replace magic numbers with
static finalor config. - Group related constants in one class or
.envfor deployment-specific values. - Document units—
TIMEOUT_MS = 5000not bare5000.
java
private static final int MAX_LOGIN_ATTEMPTS = 5;
private static final Duration LOCKOUT = Duration.ofMinutes(15);Interview tip: Constants improve readability and security audits—secrets never belong as literals in git.