JVM Knowledge

A local variable declaration statement declares one or more local variable names.

LocalVariableDeclarationStatement:
  LocalVariableDeclaration ;

LocalVariableDeclaration:
  {VariableModifier} LocalVariableType VariableDeclaratorList

LocalVariableType:
  UnannType
  var

See §8.3 for UnannType. The following productions from §4.3, §8.3, and §8.4.1 are shown here for convenience:

VariableModifier:
  Annotation
  final

VariableDeclaratorList:
  VariableDeclarator {, VariableDeclarator}

VariableDeclarator:
  VariableDeclaratorId [= VariableInitializer]

VariableDeclaratorId:
  Identifier [Dims]

Dims:
  {Annotation} [ ] {{Annotation} [ ]}

VariableInitializer:
  Expression
  ArrayInitializer

Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.

Apart from local variable declaration statements, a local variable can be declared by the header of a basic for statement (§14.14.1), an enhanced for statement (§14.14.2), or a try-with-resources statement (§14.20.3).

The rules for annotation modifiers on a local variable declaration are specified in §9.7.4 and §9.7.5.

It is a compile-time error if final appears more than once as a modifier for a local variable declaration.

It is a compile-time error if the LocalVariableType is var and any of the following are true:

  • More than one VariableDeclarator is listed.
  • The VariableDeclaratorId has one or more bracket pairs.
  • The VariableDeclarator lacks an initializer.
  • The initializer of the VariableDeclarator is an ArrayInitializer.
  • The initializer of the VariableDeclarator contains a reference to the variable.

Example 14.4-1. Local Variables Declared With var

The following code illustrates these rules restricting the use of var:

var a = 1;            // Legal
var b = 2, c = 3.0;   // Illegal: multiple declarators
var d[] = new int[4]; // Illegal: extra bracket pairs
var e;                // Illegal: no initializer
var f = { 6 };        // Illegal: array initializer
var g = (g = 7);      // Illegal: self reference in initializer

These restrictions help to avoid confusion about the type being represented by var.

14.4.1. Local Variable Declarators and Types

Each declarator in a local variable declaration declares one local variable, whose name is the Identifier that appears in the declarator.

If the optional keyword final appears at the start of the declaration, the variable being declared is a final variable (§4.12.4).

The type of a local variable is determined as follows:

  • If LocalVariableType is an UnannType, and no bracket pairs appear in UnannType or VariableDeclaratorId, then UnannType denotes the type of the local variable.

  • If LocalVariableType is an UnannType, and bracket pairs appear in UnannType or VariableDeclaratorId, then the type of the local variable is specified by §10.2.

  • If LocalVariableType is var, then let T be the type of the initializer expression when treated as if it did not appear in an assignment context, and were thus a standalone expression (§15.2). The type of the local variable is the upward projection of T with respect to all synthetic type variables mentioned by T (§4.10.5).

    It is a compile-time error if T is the null type.

    Because the initializer is treated as if it did not appear in an assignment context, an error occurs if it is a lambda expression (§15.27) or a method reference expression (§15.13).

Example 14.4.1-1. Type of Local Variables Declared With var

The following code illustrates the typing of variables declared with var:

var a = 1;                // a has type 'int'
var b = java.util.List.of(1, 2);  // b has type 'List<Integer>'
var c = "x".getClass();   // c has type 'Class<? extends String>'
                          // (see JLS 15.12.2.6)
var d = new Object() {};  // d has the type of the anonymous class
var e = (CharSequence & Comparable<String>) "x";
                          // e has type CharSequence & Comparable<String>
var f = () -> "hello";    // Illegal: lambda not in an assignment context
var g = null;             // Illegal: null type

Note that some variables declared with var cannot be declared with an explicit type, because the type of the variable is not denotable.

Upward projection is applied to the type of the initializer when determining the type of the variable. If the type of the initializer contains capture variables, this projection maps the type of the initializer to a supertype that does not contain capture variables.

While it would be possible to allow the type of the variable to mention capture variables, by projecting them away we enforce an attractive invariant that the scope of a capture variable is never larger than the statement containing the expression whose type is captured. Informally, capture variables cannot "leak" into subsequent statements.

A local variable of type float always contains a value that is an element of the float value set (§4.2.3); similarly, a local variable of type double always contains a value that is an element of the double value set. It is not permitted for a local variable of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a local variable of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

The scope and shadowing of a local variable declaration is specified in §6.3 and §6.4.

14.4.2. Execution of Local Variable Declarations

A local variable declaration statement is an executable statement. Every time it is executed, the declarators are processed in order from left to right. If a declarator has an initializer, the initializer is evaluated and its value is assigned to the variable.

If a declarator does not have an initializer, then every reference to the variable must be preceded by execution of an assignment to the variable, or a compile-time error occurs by the rules of §16 (Definite Assignment).

Each initializer (except the first) is evaluated only if evaluation of the preceding initializer completes normally.

Execution of the local variable declaration completes normally only if evaluation of the last initializer completes normally.

If the local variable declaration contains no initializers, then executing it always completes normally.