Search⌘ K

Constants

Learn the concept of constants in Java, including how to use both unnamed literals and named constants effectively. Understand the rules for numeric, character, string, and Boolean literals, and how naming constants with the final keyword helps avoid errors and improves code clarity. This lesson helps you write programs that use fixed values correctly and meaningfully.

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,
...