Constants

In this lesson, we will look at constants, values in a program that do not change.

Numeric, character, string, or Boolean values within a Java program that remain unchanged, or constant, during program execution can either have a name or be unnamed.

Unnamed constants

Earlier, we defined a literal as the Java representation of a specific fixed value, that is, a value that does not change. They are, in fact, unnamed constants. Literals conform to certain rules according to their data type:

  • Integer literals are a sequence of digits without a decimal point or commas but can have a plus or minus sign. For example, 10 and –52 are integer literals.
  • Floating-point literals are real numbers without commas but can have a plus or minus sign. They are written in one of two ways:
    • Without an exponent but with a decimal point. For example, 3.14, 0.07, and -50.0 are floating-point literals.
    • With an exponent. For example, in mathematics, we might write 0.00001234 as 12.34 × 10–6. In Java, we could write this value as 12.34e-6. The letter e, which means “exponent”, represents both the multiplication operator and the 10. The number after the e is an integer without a decimal point or comma. A plus sign is optional for positive exponents.
    • We can omit the decimal point in the number before the e, as long as we adjust the exponent to produce the correct value.
  • Character literals are single characters enclosed in single quotes.
  • String literals are sequences of characters enclosed in double quotes.
  • Boolean literals are the values true and false.

Get hands-on with 1400+ tech skills courses.