Home  >  Article  >  Java  >  An in-depth explanation of the naming rules and specifications of Java identifiers

An in-depth explanation of the naming rules and specifications of Java identifiers

PHPz
PHPzOriginal
2024-02-01 08:42:06460browse

An in-depth explanation of the naming rules and specifications of Java identifiers

Java identifier naming rules analysis: naming specifications, detailed rules

Java identifiers are used to identify variables, methods, classes and packages The name. Java identifiers must follow the following naming convention:

  • begins with a letter, an underscore (_), or a dollar sign ($).
  • cannot start with a number.
  • cannot contain spaces.
  • cannot contain special characters except underscore (_) and dollar sign ($).
  • cannot be a Java keyword.
  • cannot be the same as the Java built-in type name.

Java identifiers can be of any length, but short and meaningful names are recommended.

Detailed explanation of Java identifier naming rules

  1. The first letter is lowercase, and the first letter of subsequent words is capitalized.
// 正确的标识符
int myVariable;
String myString;

// 错误的标识符
int MYVARIABLE;
String MyString;
  1. Use underscores (_) to separate words.
// 正确的标识符
int my_variable;
String my_string;

// 错误的标识符
int myvariable;
String mystring;
  1. Avoid using Java keywords.

The Java keyword is a predefined identifier in the Java language and cannot be used as the name of a variable, method, class or package.

// 正确的标识符
int a;
String b;

// 错误的标识符
int abstract;
String boolean;
  1. Avoid using Java built-in type names.

Java built-in type names are predefined type names in the Java language and cannot be used as names of variables, methods, classes or packages.

// 正确的标识符
int a;
String b;

// 错误的标识符
int int;
String String;
  1. Use short and meaningful names.

Java identifiers should be short and meaningful for easy reading and understanding.

// 正确的标识符
int age;
String name;

// 错误的标识符
int a;
String n;

Java identifier naming convention example

// 正确的标识符
int myVariable;
String myString;
double myDouble;
boolean myBoolean;

// 错误的标识符
int 1myVariable;
String MyString;
double my-double;
boolean my_boolean;

Summary of Java identifier naming rules

Java identifier naming rules can Helps you write readable, maintainable code. Following these rules will make your code easier to understand and modify.

The above is the detailed content of An in-depth explanation of the naming rules and specifications of Java identifiers. 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