Skip to main content
Engineering LibreTexts

11.5: Literals and Constants

  • Page ID
  • A value that appears in a program, like 2.54 (or " in ="), is called a literal. In general, there’s nothing wrong with literals. But when numbers like 2.54 appear in an expression with no explanation, they make code hard to read. And if the same value appears many times, and might have to change in the future, it makes code hard to maintain.

    Values like that are sometimes called magic numbers (with the implication that being “magic” is not a good thing). A good practice is to assign magic numbers to variables with meaningful names, like this:

    double cmPerInch = 2.54;
    cm = inch * cmPerInch;

    This version is easier to read and less error-prone, but it still has a problem. Variables can vary, but the number of centimeters in an inch does not. Once we assign a value to cmPerInch, it should never change. Java provides a language feature that enforces that rule, the keyword final.

    final double CM_PER_INCH = 2.54;

    Declaring that a variable is final means that it cannot be reassigned once it has been initialized. If you try, the compiler reports an error. Variables declared as final are called constants. By convention, names for constants are all uppercase, with the underscore character (_) between words.

    • Was this article helpful?