Java Variable Naming Rules
In Java, different types of variables (such as instance variables, local variables, static variables, etc.) have certain 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 that accurately reflect the variable's purpose. Avoid single characters or meaningless abbreviations.
-
Camel Case: Use camel case in variable names, i.e., capitalize the first letter of each word, with all words except the first capitalized. For example:
myVariableName. -
Avoid keywords: Do not use Java keywords (such as 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 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; should start with a lowercase letter.
- Uppercase snake case can also usually be used, with all uppercase letters and words separated by underscores.
- Variable names should be descriptive and clearly indicate their purpose.
// Use camelCase naming convention
public static int myStaticVariable;
// Use UPPER_SNAKE_CASE
public static final int MAX_SIZE = 100;
Constant
- Use all uppercase letters, with words separated by underscores.
- Constants usually use
finalmodifier.
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 {
// Class members and methods
}