Java 变量命名规则

标识符的合法字符、禁用关键字与常见命名约定。

Beginner
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
true
These 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.

KindStyleExample
Class / InterfacePascalCaseUserService
Method / VariablecamelCasegetUserName
ConstantUPPER_SNAKE_CASEMAX_RETRY_COUNT
Packagelowercasecom.example.demo
Type parameterSingle capitalT, 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

Friends & Partners