Java Language Reference

Previous Chapter 6 Next

6. Statements and Control Structures

Labeled Statements
The Empty Statement
Expression Statements
The if Statement
The switch Statement
Iteration Statements
The break Statement
The continue Statement
The return Statement
The throw Statement
The try Statement
The synchronized Statement

A statement is the construct used to control the flow of program execution in Java:

[Graphic: Figure from the text]

Statements are executed in sequence, unless a statement alters the flow of control. Statements usually correspond to executable code.

References Blocks; The break Statement; The continue Statement; The Empty Statement; Expression Statements; The if Statement; Iteration Statements; Labeled Statements; The return Statement; The switch Statement; The synchronized Statement; The throw Statement; The try Statement

6.1 Blocks

A block is a sequence of zero or more statements, local variable declarations, or local class declarations enclosed in curly braces:

[Graphic: Figure from the text]

The bodies of methods, constructors, static initializers, and instance initializers are blocks. A variable declaration in a block causes a local variable to be defined, while a class declaration in a block causes a local class to be defined. A block is itself a kind of statement, so a block can contain other blocks. Here is an example of a block:

    int tmp = x;
    x = y;
    y = tmp;

The statements in a block are executed in the sequence in which they occur, unless a statement that alters the sequence of execution is executed. If, as a result of such a statement, the Java compiler can determine that a statement will never be executed, the compiler is required to produce an error message about the unreachable statement.

The one exception to this rule allows if statements that have constant Boolean expressions. The compiler recognizes if statements that have constant Boolean expressions and does not generate code for the portion of the statement that can never be executed. This mechanism can be used for conditional compilation; it is similar to the C/C++ preprocessor features that are used for this purpose.

References Constant Expressions; Constructors; Instance Initializers; Local Classes; Local Variables; Methods; Statement 6; Static Initializers; The switch Statement

Local Variables

Local variables declared in a block exist only from their declaration to the end of the block. A local variable declaration cannot include any modifiers except the final modifier. In other words, a variable declaration in a block cannot include any of the following keywords: public, protected, private, static, transient, or volatile. The syntax that permits the use of the final modifier with local variables is new as of Java 1.1; the usage is not permitted with earlier versions of the language.

The syntax of a local variable declaration is:

[Graphic: Figure from the text]

A local variable declaration is really made up of two distinct things:

A local variable declared within a block that has an initializer is initialized when its declaration is executed. Within the body of a method or constructor, its formal parameters are treated as local variables. Formal parameters are initialized when a method is called. A local variable can also be declared in the header of a for statement.

The following are some examples of local variable declarations:

int x;
double[] k, m[];

References Variable initializers; Expression 4; Identifiers; Interface Variables; Type 3; The for Statement; Variables

Final local variables

If a local variable is declared with the final modifier, the variable is a named constant value. As such, it must be assigned an initial value. Any assignment to a final local variable, other than the one that provides its initial value, is a compile-time error. The initial value for a final local variable is typically provided by an initializer that is part of the variable's declaration. For example:

final int X = 4;

A final local variable that is not initialized in its declaration is called a blank final. A blank final must be assigned a value exactly once. The compiler uses flow analysis that takes if statements and iteration statements into account to ensure that a blank final is assigned a value exactly once. Thus, it is possible to have multiple assignments to a blank final, so long as exactly one of them can be executed. For example, here is an instance initializer that sets the value of a blank final:

    final int DAYS_IN_YEAR;
    if (isLeapYear(new Date()))
        DAYS_IN_YEAR = 366;
        DAYS_IN_YEAR = 365;

Local variables that are declared final are not supported prior to Java 1.1.

References Instance Initializers; The do Statement; The for Statement; The if Statement; The while Statement; Variable modifiers

Local variable type

A local variable declaration must always specify the type of the variable. If the declaration of a local variable uses a primitive type, the variable contains a value of the specified primitive type. If the declaration uses a reference type, the variable contains a reference to the specified type of object.

The presence of square brackets in a variable declaration, after either the type or the variable name, indicates that the variable contains a reference to an array. For example:

int a[];        // a is an array of int
int[] b;        // b is also an array of int

It is also possible to declare a variable to contain an array of arrays, or more generally, arrays nested to any level. Each pair of square brackets in the declaration corresponds to a dimension of the array; it makes no difference whether the brackets appear after the type or the variable name. For example:

int[][][] d3;      // Each of these is an array of
int[][] f3[];      // arrays of arrays of integers
int[] g3[][];
int h3[][][];
int[] j3, k3[];    // An array and an array of arrays

References Array Types; Primitive Types; Reference Types

Local variable name

The identifier that follows the variable type is the name of the local variable. When a local variable definition is in effect, all occurrences of that name are taken to mean the local variable. If a local variable is declared with the same name as a class, an interface, or a field of the class in which the local variable is declared, the definition of the class, interface, or field is hidden. Fields that are hidden by a local variable can be referenced using the keyword this. For example:

class myClass {
    int value;
    void doit(int x) {
        int value;
        value = x*4;               // Set local variable
        this.value = value + 1;    // Set field variable

A block cannot have multiple local variables with the same name. This means that a local variable cannot be declared at a point in a block where a local variable with the same name is already defined. For example, consider the following code:

myMethod(char c){
    int j;        // Okay
    char c;       // Error
    int j;        // Error
        int j;    // Error
        int x;    // Okay
        int x;    // Okay
    int x;        // Okay

In the above example, the declaration of c as a local variable is an error because it occurs in a method that has a formal parameter with that name. The second declaration of j is an error because there is already a local variable defined with that name. The third declaration of j as a local variable is also an error for the same reason; the nested block sees all of the declarations that are visible in the enclosing block, including the declaration of j in the outer block.

The first declaration of x is fine because there is no previous declaration of x for it to conflict with. The second declaration of x is also fine because there is no previous declaration of x in the enclosing block for it to conflict with. The first declaration of x occurs in a nested block, so it is not visible in the enclosing block. The third declaration of x is also fine because the preceding declarations occurred in nested blocks; they are not visible in the enclosing block.

References Identifiers; this

Local variable initializers

A local variable declaration can contain an initializer. If the variable is of a non-array type, the expression in the initializer is evaluated and the variable is set to the result of the expression, as long as the result is assignment-compatible with the variable. If the variable is of an array type, the initializer must be an array initializer, as described in Variable initializers. If the variable is declared final, the initializer sets the value of the named constant.

A local variable declaration with an initializer is similar in effect to a local variable declaration without an initializer immediately followed by an assignment statement that sets the declared variable. Take the following example:

int a = 4;

This is equivalent to:

int a;
a = 4;

If a local variable has an initializer, the value of the variable is set to the value of the initializer when the declaration is executed.

Any attempt to access the value of a local variable before its value is set by an assignment statement or an initializer is treated as an error by the Java compiler. For example:

int foo(int x) {
    int a = x + 1;
    int b, c;
    if (a > 4)
        b = 3;
    a = a * c;        // Error: c not initialized
    a = b * 8 + a;    // Error: b might not be initialized

This example contains two errors. First, the compiler complains about the expression a*c because c is not initialized. The compiler also complains about the expression b* 8+a because the preceding assignment to b may not executed, depending on the value of a. If the compiler cannot guarantee that a local variable will be initialized, it generates an error message when the variable is used.

References Variable initializers; Assignment Operators

Local Classes

Local classes declared in a block exist only in the scope of that block. Local classes are not supported prior to Java 1.1 Here's the syntax of a local class declaration:

[Graphic: Figure from the text]

A local class can access local variables in the enclosing block that are declared final. A local class can also access instance variables of the enclosing class if they are not declared inside of a static method or static initializer.

There is an alternate syntax for a local class that allows an anonymous local class to be defined. This syntax is available as part of an allocation expression.

References Allocation Expressions; Anonymous classes; Local classes; Local Variables; Class Declarations; Variables

Local class modifiers

The keywords abstract and final can be used in the declaration of a local class. These modifiers have the following meanings:


If a local class is declared abstract, no instances of the class may be created. A local class declared abstract may contain abstract methods. Classes not declared abstract may not contain abstract methods and must override any abstract methods they inherit with methods that are not abstract. Classes that implement an interface and are not declared abstract must contain or inherit methods that are not abstract that have the same name, have the same number of parameters, and have corresponding parameter types as the methods declared in the interfaces that the class implements.


If a local class is declared final, it cannot be subclassed. In other words, it cannot appear in the extends clause of another class.

References Class Modifiers; Inner class modifiers

Local class members

The body of a local class cannot declare any static variables, static methods, static classes, or static initializers. Beyond those restrictions, the remainder of the declaration is the same as that for a top-level class declaration, which is described in Class Declarations.

References Class Declarations; Constructors; Instance Initializers; Methods; Nested Top-Level and Member Classes; Static Initializers; Variables

Previous Home Next
Interface Declarations Book Index Labeled Statements

Java in a Nutshell Java Language Reference Java AWT Java Fundamental Classes Exploring Java