Java Constant Definition: The final Keyword and Constants, Avoiding Reassignment

In Java programming, we often need to define some fixed values, such as “a class can have at most 30 students” or “the default port number of a website is 8080”. These values do not change during program execution, and we call them “constants”. In Java, the most common way to define constants is by using the final keyword.

I. What are Constants?

A constant is a variable whose value cannot be modified once it is assigned. The difference between a constant and a regular variable is: the value of a regular variable can be changed at any time, while the value of a constant is “read-only”.

II. How to Define Constants with final?

In Java, the final keyword is used to modify variables, making them constants. The syntax for defining constants is very straightforward:

final dataType constantName = initialValue;

For example:

// Define an integer constant representing the maximum age
final int MAX_AGE = 18;

// Define a string constant representing the website name
final String SITE_NAME = "Java Tutorial";

III. Precautions for Defining Constants

  1. Must Be Initialized
    Since a constant cannot be modified once defined, it must be assigned a value during declaration. If declared without assignment, the compiler will throw an error:
   final int NUM; // Error! Uninitialized final variable cannot be defined
   NUM = 100;     // Error! Even if assigned here, the previous declaration is invalid
  1. Cannot Be Reassigned
    The value of a constant cannot be changed. Attempting to modify it will directly cause an error:
   final int COUNT = 5;
   COUNT = 10; // Error! Cannot assign a value to a final variable COUNT

IV. Why Use Constants?

The core purpose of using final to define constants is to avoid repeated assignments and improve code reliability:
- Prevent Accidental Modifications: If a constant is accidentally modified, the compiler will throw an error, preventing potential issues early.
- Improve Readability: Constant names are typically in uppercase with underscores (e.g., MAX_AGE), making it obvious that they are fixed values and easier to understand the code logic.
- Facilitate Maintenance: If the constant value needs to be changed (e.g., changing “18 years old” to “20 years old”), it only needs to be modified once at the definition point, and all places using this constant will be updated automatically.

V. Class Constants (Global Constants)

If a constant needs to be shared across multiple classes (e.g., global configurations, fixed parameters), it can be defined as a “class constant” using the combination of static final. For example:

public class AppConfig {
    // Class constants: accessible directly by all classes
    public static final String DB_URL = "jdbc:mysql://localhost:3306/test";
    public static final int TIME_OUT = 30; // Timeout (seconds)
}

Other classes can access them directly via the class name:

// Using class constants
String url = AppConfig.DB_URL;
int timeout = AppConfig.TIME_OUT;

VI. Common Misconceptions

  • final-Modified Variables Are Not Always Constants: A final variable is not necessarily a constant if it is not assigned or modified (though Java does not allow modification). In practice, a final variable becomes a constant only if it is assigned once and never modified again.
  • Object References and Constants: For an object reference modified by final (e.g., final Person p), the reference address cannot be changed, but the internal properties of the object can still be modified (e.g., p.setName("Zhang San") is valid).

VII. Summary

  • Constant Definition: Use the final keyword; it must be assigned a value during declaration and cannot be modified.
  • Naming Convention: Constant names are recommended to be all uppercase with underscores for multiple words (e.g., MAX_SIZE).
  • Benefits: Prevents accidental modifications, improves readability and maintainability.

By using final to define constants, you can make your code more robust and clear, reducing bugs caused by accidental value changes. As a beginner, mastering this basic syntax is essential!

Xiaoye