JVM Knowledge

A declaration introduces one of the following entities into a program:

  • A module, declared in a module declaration (§7.7)

  • A package, declared in a package declaration (§7.4)

  • An imported class or interface, declared in a single-type-import declaration, a type-import-on-demand declaration, or a single-module-import declaration (§7.5.1, §7.5.2, §7.5.5)

  • 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 by a normal class declaration (§8.1), an enum declaration (§8.9), a record declaration (§8.10), or implicitly by a compact compilation unit (§7.3)

  • An interface, declared by a normal interface declaration (§9.1) or an annotation interface declaration (§9.6).

  • 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)

    • A field, one of the following:

      • A field declared in a class (§8.3)
      • A field declared in an interface (§9.3)
      • An implicitly declared field of a class corresponding to an enum constant or a record component
      • 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 (§8.4)
      • A method (abstract or otherwise) declared in an interface (§9.4)
      • An implicitly declared accessor method corresponding to a record component
  • An enum constant (§8.9.1)

  • A record component (§8.10.3)

  • A formal parameter, one of the following:

    • A formal parameter of a method of a class or interface (§8.4.1)
    • A formal parameter of a constructor of a class (§8.8.1)
    • A formal parameter of a lambda expression (§15.27.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 by a local variable declaration statement in a block (§14.4.2)
    • A local variable declared by a for statement or a try-with-resources statement (§14.14, §14.20.3)
    • A local variable declared by a pattern (§14.30.1)
  • A local class or interface (§14.3), one of the following:

    • A local class declared by a normal class declaration
    • A local class declared by an enum declaration
    • A local class declared by an record declaration
    • A local interface declared by a normal interface declaration

Constructors (§8.8, §8.10.4) are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.

A declaration commonly includes an identifier (§3.8) that can be used in a name to refer to the declared entity. The identifier is constrained to avoid certain contextual keywords when the entity being introduced is a class, interface, or type parameter.

If a declaration does not include an identifier, but instead includes the keyword _ (underscore), then the entity cannot be referred to by name. The following kinds of entity may be declared using an underscore:

  • A local variable, one of the following:

    • A local variable declared by a local variable declaration statement (§14.4.2)
    • A local variable declared by a for statement or a try-with-resources statement (§14.14, §14.20.3)
    • A local variable declared by a pattern (§14.30.1)
  • An exception parameter of an exception handler declared in a catch clause of a try statement (§14.20)

  • A formal parameter of a lambda expression (§15.27.1)

A local variable, exception parameter, or lambda parameter that is declared using an underscore is called an unnamed local variable, unnamed exception parameter, or unnamed lambda parameter, respectively.

The declaration of a generic class or interface (class C<T> ... or interface C<T> ...) introduces both a class named C and a family of types: the raw type C, the parameterized type C<Foo>, the parameterized type C<Bar>, etc.

When a reference to C occurs where genericity is unimportant, identified below as one of the non-generic contexts, the reference to C denotes the class or interface C. In other contexts, the reference to C denotes a type, or part of a type, introduced by C.

The 15 non-generic contexts are as follows:

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

The first twelve non-generic contexts correspond to the first twelve syntactic contexts for a TypeName in §6.5.1. The thirteenth 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 thirteen contexts is significant: it indicates that these contexts involve a less-than-first-class use of a type. In contrast, the fourteenth and fifteenth non-generic contexts employ ClassType, indicating that throws and catch clauses use types in a first-class way, in line with, for example, field declarations. The characterization of these two contexts as non-generic is due to the fact that an exception type cannot be parameterized (§8.1.2).

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, for example, 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

Programmers 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 Names

Names of class 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
ProcessBuilder
Thread
Dictionary
BufferedInputStream

Likewise, names of interface 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 classes and interfaces 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 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 interfaces should be, and final variables of classes 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.