JVM Knowledge

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 package, declared in a package declaration (§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 static member, 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:

    • A member class (§8.5, §9.5)

    • A member interface (§8.5, §9.5)

    • An enum constant (§8.9)

    • A field, one of the following:

      • A field declared in a class type or enum type (§8.3, §8.9.2)
      • A field declared in an interface type or annotation type (§9.3, §9.6.1)
      • The field length, which is implicitly a member of every array type (§10.7)
    • A method, one of the following:

      • A method (abstract or otherwise) declared in a class type or enum type (§8.4, §8.9.2)
      • A method (always abstract) declared in an interface type or annotation type (§9.4, §9.6.1)
  • 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 abstract method of an interface type or annotation type (§9.4, §9.6.1)
    • An exception parameter of an exception handler declared in a catch clause of a try statement (§14.20)
  • A local variable, one of the following:

    • A local variable declared in a block (§14.4)
    • A local variable declared in a for statement (§14.14)

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 C denotes the non-generic type C.

  • If genericity is important, as in all contexts from §6.5 except the non-generic contexts, the identifier C denotes either:

    • The raw type C which is the erasure (§4.6) of the generic type C<T>; or
    • A parameterized type which is a particular parameterization (§4.5) of the generic type C<T>.

The 13 non-generic contexts are as follows:

  1. In a single-type-import declaration (§7.5.1)
  2. To the left of the . in a single-static-import declaration (§7.5.3)
  3. To the left of the . in a static-import-on-demand declaration (§7.5.4)
  4. To the left of the ( in a constructor declaration (§8.8)
  5. After the @ sign in an annotation (§9.7)
  6. To the left of .class in a class literal (§15.8.2)
  7. To the left of .this in a qualified this expression (§15.8.4)
  8. To the left of .super in a qualified superclass field access expression (§15.11.2)
  9. To the left of .Identifier or .super.Identifier in a qualified method invocation expression (§15.12)
  10. To the left of .super:: in a method reference expression (§15.13)
  11. In a qualified expression name in a postfix expression (§15.14.1)
  12. In a throws clause of a method or constructor (§8.4.6, §8.8.5, §9.4)
  13. In an exception parameter declaration (§14.20)

The first ten non-generic contexts correspond to the first ten syntactic contexts for a TypeName in §6.5.1. The eleventh non-generic context is a postfix expression, where a qualified ExpressionName such as C.x may include a TypeName C to denote static member access. The common use of TypeName is significant: it indicates that these contexts involve a less-than-first-class use of a type. In contrast, the twelfth and thirteenth 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

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 class ClassLoader 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.java.jag.scrabble
org.openjdk.tools.compiler
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.

The name of a package is not meant to imply where the package is stored on the Internet. The suggested convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for package names.

For example, a package named edu.cmu.cs.bovik.cheese is not necessarily obtainable from Internet address cmu.edu or cs.cmu.edu or bovik.cs.cmu.edu.

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.

Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved for packages of the Java SE platform.

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-2. 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-3. 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 getV and setV. An example is the methods getPriority and setPriority of class Thread.
  • A method that returns the length of something should be named length, as in class String.
  • A method that tests a boolean condition V about an object should be named isV. An example is the method isInterrupted of class Thread.
  • A method that converts its object to a particular format F should be named toF. Examples are the method toString of class Object and the methods toLocaleString and toGMTString of class java.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 cp for a variable holding a reference to a ColoredPoint

  • Abbreviations, as in buf holding 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:

    • in and out, whenever some kind of input and output are involved, patterned after the fields of System
    • off and len, whenever an offset and length are involved, patterned after the parameters to the read and write methods of the interfaces DataInput and DataOutput of java.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:

  • b for a byte
  • c for a char
  • d for a double
  • e for an Exception
  • f for a float
  • i, j, and k for ints
  • l for a long
  • o for an Object
  • s for a String
  • v for 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.