Java 变量命名规则
标识符的合法字符、禁用关键字与常见命名约定。
Key Points首字符不能是数字,不能用关键字,区分大小写;类 PascalCase、方法与变量 camelCase、常量 UPPER_SNAKE。
命名规则
An identifier may contain letters, digits, _ and $, but cannot start with a digit. Keywords are forbidden, case matters, and length is unlimited.
Java
public class Rules {
public static void main(String[] args) {
int age = 1;
int _count = 2;
int $price = 3;
int userName2 = 4;
System.out.println(age + _count + $price + userName2);
System.out.println(age == 1);
}
}Output
10
trueThese are illegal:
2name (starts with a digit), user-name (hyphen), class (keyword), user name (space). Your IDE marks them red immediately.命名约定
Beyond the rules there are conventions: breaking them compiles fine but upsets reviewers. Classes and interfaces use PascalCase, methods and variables camelCase, constants UPPER_SNAKE, packages lowercase.
| Kind | Style | Example |
|---|---|---|
| Class / Interface | PascalCase | UserService |
| Method / Variable | camelCase | getUserName |
| Constant | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| Package | lowercase | com.example.demo |
| Type parameter | Single capital | T, E, K, V |
Java
public class Naming {
static final int MAX_RETRY_COUNT = 3;
private String userName;
public String getUserName() {
return userName;
}
public static void main(String[] args) {
Naming n = new Naming();
n.userName = "tom";
System.out.println(n.getUserName());
System.out.println(MAX_RETRY_COUNT);
}
}Output
tom
3命名规则
标识符只能由字母、数字、_、$ 组成,且首字符不能是数字。不能用关键字(class、int、new 等),区分大小写,长度不限。
Java
public class Rules {
public static void main(String[] args) {
int age = 1;
int _count = 2;
int $price = 3;
int userName2 = 4;
System.out.println(age + _count + $price + userName2);
System.out.println(age == 1);
}
}Output
10
true下面这些都不合法:
2name(数字开头)、user-name(含连字符)、class(关键字)、user name(含空格)。IDE 会直接标红。命名约定
规则之外还有约定,违反不会编译失败但会被同事吐槽。类与接口用大驼峰,方法与变量用小驼峰,常量全大写,包名全小写。
| 种类 | 风格 | 示例 |
|---|---|---|
| 类 / 接口 | 大驼峰 | UserService |
| 方法 / 变量 | 小驼峰 | getUserName |
| 常量 | 全大写下划线 | MAX_RETRY_COUNT |
| 包 | 全小写 | com.example.demo |
| 泛型参数 | 单个大写字母 | T, E, K, V |
Java
public class Naming {
static final int MAX_RETRY_COUNT = 3;
private String userName;
public String getUserName() {
return userName;
}
public static void main(String[] args) {
Naming n = new Naming();
n.userName = "tom";
System.out.println(n.getUserName());
System.out.println(MAX_RETRY_COUNT);
}
}Output
tom
3