Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Easy · Free

What are literals, constants, and magic numbers? Why avoid magic numbers?

FresherFundamentalsProgramming Fundamentals
Model answer

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 final or config.
  • Group related constants in one class or .env for deployment-specific values.
  • Document units—TIMEOUT_MS = 5000 not bare 5000.
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.