Java identifier naming rules
- Letters, numbers, underscores, dollar signs ($)
- cannot start with a number
- cannot be a Java keyword
- cannot be used with classes or classes in the Java class library Method and variable name conflicts
- It is recommended to use camel case naming method
- Variable names should be short and meaningful
- Constant names should be in all uppercase letters, with underscores separating words
Naming Tips
-
Use descriptive Name: Variable names should clearly describe what the variable does. For example, a variable that stores a username could be named
username
.
-
Use a consistent naming style: Use a consistent naming style throughout the project to make it easier to read and understand the code. For example, you can use camelCase or underscore case.
-
Avoid using abbreviations: Abbreviations can make code difficult to read and understand. For example, don't abbreviate
username
to un
.
-
Avoid using special characters: Special characters can make code difficult to read and understand. For example, don't use spaces or exclamation points in variable names.
Note
-
Do not use Java keywords: Java keywords are special words used to represent language structures . For example,
if
, else
, and for
are Java keywords. You cannot name a variable or method name as a Java keyword.
-
Do not conflict with the names of classes, methods, and variables in the Java class library: The Java class library contains many classes, methods, and variables. You cannot name a variable or method name that conflicts with a class, method, or variable name in a Java class library.
-
Don’t use confusing names: Don’t use confusing names to avoid making the code difficult to read and understand. For example, do not confuse
l
with 1
, and do not confuse O
with 0
.
Code Example
// 使用描述性名称
String username = "john.doe";
// 使用一致的命名风格
int age = 30;
double salary = 50000.00;
// 避免使用缩写
String firstName = "John";
String lastName = "Doe";
// 避免使用特殊字符
String address = "123 Main Street";
// 不要使用 Java 关键字
int if = 10; // 错误:if 是 Java 关键字
// 不要与 Java 类库中的类、方法、变量名冲突
String System = "System"; // 错误:System 是 Java 类库中的类
// 不要使用易混淆的名称
int l = 1; // 错误:l 和 1 容易混淆
int O = 0; // 错误:O 和 0 容易混淆
The above is the detailed content of An in-depth look at Java identifier naming conventions: a comprehensive guide including naming tips and considerations. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn