Java Constants: Naming Rules & Best Practices
The naming rules for Java constants are as follows:
- Constant names should be written in all capital letters with underscores “_” separating multiple words.
- Constant names should be descriptive and able to clearly convey their meanings.
- Constant naming should follow the camel case convention, where the first letter of each word is capitalized and the following letters are lowercase (constants with only one word can be all uppercase).
- Abbreviations and shorthand should be avoided when naming constants, unless the abbreviation is well-known.
- Constant names should avoid using numbers as much as possible, unless the numbers have a specific meaning in semantics.
Here are some examples of naming constants:
public static final int MAX_LENGTH = 100;
public static final String ERROR_MESSAGE = "Invalid input";
public static final String STUDENT_NAME = "John Doe";
public static final double PI = 3.14159;
public static final int DAYS_IN_WEEK = 7;
Please note that Java constants are typically declared using the final keyword to ensure that their values cannot be changed.