A declaration introduces an entity into a program and includes an identifier (§3.8) that can be used in a name to refer to this entity.
A declared entity is one of the following:
-
A module, declared in a
moduledeclaration (§7.7) -
A package, declared in a
packagedeclaration (§7.4) -
An imported type, declared in a single-type-import declaration or a type-import-on-demand declaration (§7.5.1, §7.5.2)
-
An imported
staticmember, declared in a single-static-import declaration or a static-import-on-demand declaration (§7.5.3, §7.5.4) -
A class, declared in a class type declaration (§8.1)
-
An interface, declared in an interface type declaration (§9.1)
-
A type parameter, declared as part of the declaration of a generic class, interface, method, or constructor (§8.1.2, §9.1.2, §8.4.4, §8.8.4)
-
A member of a reference type (§8.2, §9.2, §8.9.3, §9.6, §10.7), one of the following:
-
An enum constant (§8.9)
-
A field, one of the following:
-
A method, one of the following:
-
A parameter, one of the following:
- A formal parameter of a method or constructor of a class type or enum type (§8.4.1, §8.8.1, §8.9.2), or of a lambda expression (§15.27.1)
- A formal parameter of an
abstractmethod of an interface type or annotation type (§9.4, §9.6.1) - An exception parameter of an exception handler declared in a
catchclause of atrystatement (§14.20)
-
A local variable, one of the following:
Constructors (§8.8) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.
The declaration of a type which is not generic (class C ...) declares one entity: a non-generic type (C). A non-generic type is not a raw type, despite the syntactic similarity. In contrast, the declaration of a generic type (class C<T> ... or interface C<T> ...) declares two entities: a generic type (C<T>) and a corresponding non-generic type (C). In this case, the meaning of the term C depends on the context where it appears:
-
If genericity is unimportant, as in the non-generic contexts identified below, the identifier
Cdenotes the non-generic typeC. -
If genericity is important, as in all contexts from §6.5 except the non-generic contexts, the identifier
Cdenotes either:
The 14 non-generic contexts are as follows:
- In a
usesorprovidesdirective in a module declaration (§7.7.1) - In a single-type-import declaration (§7.5.1)
- To the left of the
.in a single-static-import declaration (§7.5.3) - To the left of the
.in a static-import-on-demand declaration (§7.5.4) - To the left of the
(in a constructor declaration (§8.8) - After the
@sign in an annotation (§9.7) - To the left of
.classin a class literal (§15.8.2) - To the left of
.thisin a qualifiedthisexpression (§15.8.4) - To the left of
.superin a qualified superclass field access expression (§15.11.2) - To the left of
.Identifier or.super.Identifier in a qualified method invocation expression (§15.12) - To the left of
.super::in a method reference expression (§15.13) - In a qualified expression name in a postfix expression or a
try-with-resources statement (§15.14.1, §14.20.3) - In a
throwsclause of a method or constructor (§8.4.6, §8.8.5, §9.4) - In an exception parameter declaration (§14.20)
The first eleven non-generic contexts correspond to the first eleven syntactic contexts for a TypeName in §6.5.1. The twelfth non-generic context is where a qualified ExpressionName such as C.x may include a TypeName C to denote static member access. The common use of TypeName in these twelve contexts is significant: it indicates that these contexts involve a less-than-first-class use of a type. In contrast, the thirteenth and fourteenth non-generic contexts employ ClassType, indicating that throws and catch clauses use types in a first-class way, in line with, say, field declarations. The characterization of these two contexts as non-generic is due to the fact that an exception type cannot be parameterized.
Note that the ClassType production allows annotations, so it is possible to annotate the use of a type in a throws or catch clause, whereas the TypeName production disallows annotations, so it is not possible to annotate the name of a type in, say, a single-type-import declaration.
Naming Conventions
The class libraries of the Java SE Platform attempt to use, whenever possible, names chosen according to the conventions presented below. These conventions help to make code more readable and avoid certain kinds of name conflicts.
We recommend these conventions for use in all programs written in the Java programming language. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the sin and cos methods of the class java.lang.Math have mathematically conventional names, even though these method names flout the convention suggested here because they are short and are not verbs.
Package Names and Module Names
Developers should take steps to avoid the possibility of two published packages having the same name by choosing unique package names for packages that are widely distributed. This allows packages to be easily and automatically installed and catalogued. This section specifies a suggested convention for generating such unique package names. Implementations of the Java SE Platform are encouraged to provide automatic support for converting a set of packages from local and casual package names to the unique name format described here.
If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The classes ClassLoader and ModuleLayer can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve program.
You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as oracle.com. You then reverse this name, component by component, to obtain, in this example, com.oracle, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names. Such a convention might specify that certain package name components be division, department, project, machine, or login names.
Example 6.1-1. Unique Package Names
com.nighthacks.scrabble.dictionary
org.openjdk.compiler.source.tree
net.jcip.annotations
edu.cmu.cs.bovik.cheese
gov.whitehouse.socks.mousefinder
The first component of a unique package name is always written in all-lowercase ASCII letters and should be one of the top level domain names, such as com, edu, gov, mil, net, or org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166.
In some cases, the Internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations:
- If the domain name contains a hyphen, or any other special character not allowed in an identifier (§3.8), convert it into an underscore.
- If any of the resulting package name components are keywords (§3.9), append an underscore to them.
- If any of the resulting package name components start with a digit, or any other character that is not allowed as an initial character of an identifier, have an underscore prefixed to the component.
The name of a module should correspond to the name of its principal exported package. If a module does not have such a package, or if for legacy reasons it must have a name that does not correspond to one of its exported packages, then its name should still start with the reversed form of an Internet domain with which its author is associated.
Example 6.1-2. Unique Module Names
com.nighthacks.scrabble
org.openjdk.compiler
net.jcip.annotations
The first component of a package or module name must not be the identifier java. Package and module names that start with the identifier java are reserved for packages and modules of the Java SE Platform.
The name of a package or module is not meant to imply where the package or module is stored on the Internet. For example, a package named edu.cmu.cs.bovik.cheese is not necessarily obtainable from the host cmu.edu or cs.cmu.edu or bovik.cs.cmu.edu. The suggested convention for generating unique package and module names is merely a way to piggyback a package and module naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for package and module names.
Class and Interface Type Names
Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed case with the first letter of each word capitalized.
Example 6.1-3. Descriptive Class Names
ClassLoader
SecurityManager
Thread
Dictionary
BufferedInputStream
Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces java.io.DataInput and java.io.DataOutput; or it may be an adjective describing a behavior, as for the interfaces Runnable and Cloneable.
Type Variable Names
Type variable names should be pithy (single character if possible) yet evocative, and should not include lower case letters. This makes it easy to distinguish type parameters from ordinary classes and interfaces.
Container types should use the name E for their element type. Maps should use K for the type of their keys and V for the type of their values. The name X should be used for arbitrary exception types. We use T for type, whenever there is not anything more specific about the type to distinguish it. (This is often the case in generic methods.)
If there are multiple type parameters that denote arbitrary types, one should use letters that neighbor T in the alphabet, such as S. Alternately, it is acceptable to use numeric subscripts (e.g., T1, T2) to distinguish among the different type variables. In such cases, all the variables with the same prefix should be subscripted.
If a generic method appears inside a generic class, it is a good idea to avoid using the same names for the type parameters of the method and class, to avoid confusion. The same applies to nested generic classes.
Example 6.1-4. Conventional Type Variable Names
public class HashSet<E> extends AbstractSet<E> { ... }
public class HashMap<K,V> extends AbstractMap<K,V> { ... }
public class ThreadLocal<T> { ... }
public interface Functor<T, X extends Throwable> {
T eval() throws X;
}
When type parameters do not fall conveniently into one of the categories mentioned, names should be chosen to be as meaningful as possible within the confines of a single letter. The names mentioned above (E, K, V, X, T) should not be used for type parameters that do not fall into the designated categories.
Method Names
Method names should be verbs or verb phrases, in mixed case, with the first letter lowercase and the first letter of any subsequent words capitalized. Here are some additional specific conventions for method names:
- Methods to get and set an attribute that might be thought of as a variable V should be named
getVandsetV. An example is the methodsgetPriorityandsetPriorityof classThread. - A method that returns the length of something should be named
length, as in classString. - A method that tests a boolean condition V about an object should be named
isV. An example is the methodisInterruptedof classThread. - A method that converts its object to a particular format F should be named
toF. Examples are the methodtoStringof classObjectand the methodstoLocaleStringandtoGMTStringof classjava.util.Date.
Whenever possible and appropriate, basing the names of methods in a new class on names in an existing class that is similar, especially a class from the Java SE Platform API, will make it easier to use.
Field Names
Names of fields that are not final should be in mixed case with a lowercase first letter and the first letters of subsequent words capitalized. Note that well-designed classes have very few public or protected fields, except for fields that are constants (static final fields).
Fields should have names that are nouns, noun phrases, or abbreviations for nouns.
Examples of this convention are the fields buf, pos, and count of the class java.io.ByteArrayInputStream and the field bytesTransferred of the class java.io.InterruptedIOException.
Constant Names
The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech.
Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.
A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix.
For example:
interface ProcessStates {
int PS_RUNNING = 0;
int PS_SUSPENDED = 1;
}
Local Variable and Parameter Names
Local variable and parameter names should be short, yet meaningful. They are often short sequences of lowercase letters that are not words, such as:
-
Acronyms, that is the first letter of a series of words, as in
cpfor a variable holding a reference to aColoredPoint -
Abbreviations, as in
bufholding a pointer to a buffer of some kind -
Mnemonic terms, organized in some way to aid memory and understanding, typically by using a set of local variables with conventional names patterned after the names of parameters to widely used classes. For example:
inandout, whenever some kind of input and output are involved, patterned after the fields ofSystemoffandlen, whenever an offset and length are involved, patterned after the parameters to thereadandwritemethods of the interfacesDataInputandDataOutputofjava.io
One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:
bfor abytecfor achardfor adoubleefor anExceptionffor afloati,j, andkforintslfor alongofor anObjectsfor aStringvfor an arbitrary value of some type
Local variable or parameter names that consist of only two or three lowercase letters should not conflict with the initial country codes and domain names that are the first component of unique package names.