Java Variable Naming Rules
In Java, different types of variables (such as instance variables, local variables, static variables, etc.) have some naming rules and conventions.
Following some basic rules helps improve code readability and maintainability.
The following is an overview of the naming rules for various variables:
Use meaningful names:Variable names should have clear meanings and accurately reflect the purpose of the variable. Avoid using single characters or meaningless abbreviations.
Camel Case:Use camel case in variable names, that is, capitalize the first letter of each word, except for the first word, the first letters of the remaining words are capitalized. For example:
myVariableName。Avoid keywords:Do not use Java keywords (e.g., class, int, boolean, etc.) as variable names.
Case sensitivity:Java is case-sensitive, so uppercase and lowercase letters in variable names are treated as different symbols. For example,
myVariableandmyvariableare two different variables.Do not start with a number:Variable names cannot start with a number, but can contain numbers.
Follow naming conventions:For different types of variables (local variables, instance variables, static variables, etc.), different naming conventions can be used, such as using prefixes or suffixes to distinguish them.
Local Variables
- Use camel case.
- Should start with a lowercase letter.
- Variable names should be descriptive and clearly indicate their purpose.
int myLocalVariable;
Instance Variables (Member Variables)
- Use camel case.
- Should start with a lowercase letter.
- Variable names should be descriptive and clearly indicate their purpose.
private int myInstanceVariable;
Static Variables (Class Variables)
- Use camel case and should start with a lowercase letter.
- Usually, uppercase snake case can also be used, with all uppercase letters and words separated by underscores.
- Variable names should be descriptive and clearly indicate their purpose.
// 使用驼峰命名法 public static int myStaticVariable; // 使用大写蛇形命名法 public static final int MAX_SIZE = 100;
Constants
- Use all uppercase letters, with words separated by underscores.
- Constants usually use
finalfor modification.
public static final double PI = 3.14;
Parameters
- Use camel case.
- Should start with a lowercase letter.
- Parameter names should be descriptive and clearly indicate their purpose.
public void myMethod(int myParameter) {
// 方法体
}
Class Names
- Use camel case.
- Should start with an uppercase letter.
- Class names should be descriptive and clearly indicate their purpose.
public class MyClass {
// 类的成员和方法
}
Other Extensions