<html>
<head>
<title> Blocks and Statements</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="binaryComp.doc.html">Prev</a> | <a href="expressions.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<hr><br>
<a name="44383"></a>
<p><strong>
CHAPTER
14 </strong></p>
<a name="101241"></a>
<h1>Blocks and Statements</h1>
<hr><p>
<a name="45234"></a>
The sequence of execution of a program is controlled by <em>statements</em>, which are executed for their effect and do not have values.<p>
<a name="17960"></a>
Some statements <em>contain</em> other statements as part of their structure; such other statements are substatements of the statement. We say that statement <i>S</i> <em>immediately  contains</em> statement <i>U</i> if there is no statement <i>T</i> different from <i>S</i> and <i>U</i> such that <i>S</i> contains <i>T</i> and <i>T</i> contains <i>U</i>. In the same manner, some statements contain expressions <a href="expressions.doc.html#4709">(§15)</a> as part of their structure.<p>
<a name="43082"></a>
The first section of this chapter discusses the distinction between normal and abrupt completion of statements <a href="statements.doc.html#5894">(§14.1)</a>. Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.<p>
<a name="43210"></a>
Blocks are explained first <a href="statements.doc.html#246838">(§14.2)</a>, followed by local class declarations <a href="statements.doc.html#247766">(§14.3)</a> and local variable declaration statements <a href="statements.doc.html#5920">(§14.4)</a>. <p>
<a name="43203"></a>
Next a grammatical maneuver that sidesteps the familiar "dangling <code>else</code>" problem <a href="statements.doc.html#32584">(§14.5)</a> is explained.<p>
<a name="43118"></a>
Statements that will be familiar to C and C++ programmers are the empty <a href="statements.doc.html#5970">(§14.6)</a>, labeled <a href="statements.doc.html#78993">(§14.7)</a>, expression <a href="statements.doc.html#5984">(§14.8)</a>, <code>if</code> <a href="statements.doc.html#5991">(§14.9)</a>, <code>switch</code> <a href="statements.doc.html#35518">(§14.10)</a>, <code>while</code> <a href="statements.doc.html#237277">(§14.11)</a>, <code>do</code> <a href="statements.doc.html#6045">(§14.12)</a>, <code>for</code> <a href="statements.doc.html#24588">(§14.13)</a>, <code>break</code> <a href="statements.doc.html#6842">(§14.14)</a>, <code>continue</code> <a href="statements.doc.html#6122">(§14.15)</a>, and <code>return</code> <a href="statements.doc.html#6767">(§14.16)</a> statements.<p>
<a name="43199"></a>
Unlike C and C++, the Java programming language has no <code>goto</code> statement. However, the <code>break</code> and <code>continue</code> statements are allowed to mention statement labels.<p>
<a name="43200"></a>
The Java programming language statements that are not in the C language are the <code>throw</code> <a href="statements.doc.html#237350">(§14.17)</a>, <code>synchronized</code> <a href="statements.doc.html#255769">(§14.18)</a>, and <code>try</code> <a href="statements.doc.html#79311">(§14.19)</a> statements.<p>
<a name="43110"></a>
The last section <a href="statements.doc.html#236365">(§14.20)</a> of this chapter addresses the requirement that every statement be <em>reachable</em> in a certain technical sense.<p>
<a name="5894"></a>
<h2>14.1 Normal and Abrupt Completion of Statements</h2>
<a name="78796"></a>
Every statement has a normal mode of execution in which certain computational steps are carried out. The following sections describe the normal mode of execution for each kind of statement. <p>
<a name="256000"></a>
If all the steps are carried out as described, with no indication of abrupt completion, the statement is said to <em>complete normally</em>. However, certain events may prevent a statement from completing normally:<p>
<ul><a name="47062"></a>
<li>The <code>break</code> <a href="statements.doc.html#6842">(§14.14)</a>, <code>continue</code> <a href="statements.doc.html#6122">(§14.15)</a>, and <code>return</code> <a href="statements.doc.html#6767">(§14.16)</a> statements cause a transfer of control that may prevent normal completion of statements that contain them.
<a name="78802"></a>
<li>Evaluation of certain expressions may throw exceptions from the Java virtual machine; these expressions are summarized in <a href="expressions.doc.html#79448">§15.6</a>. An explicit <code>throw</code> <a href="statements.doc.html#237350">(§14.17)</a> statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.
</ul><a name="5898"></a>
If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to <em>complete abruptly</em>. <p>
<a name="255999"></a>
An abrupt completion always has an associated <em>reason</em>, which is one of the following:<p>
<ul><a name="5899"></a>
<li>A <code>break</code> with no label
<a name="78812"></a>
<li>A <code>break</code> with a given label
<a name="5901"></a>
<li>A <code>continue</code> with no label
<a name="78822"></a>
<li>A <code>continue</code> with a given label
<a name="5903"></a>
<li>A <code>return</code> with no value
<a name="5904"></a>
<li>A <code>return</code> with a given value
<a name="78827"></a>
<li>A <code>throw</code> with a given value, including exceptions thrown by the Java virtual machine
</ul><a name="237105"></a>
The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions <a href="expressions.doc.html#79448">(§15.6)</a>. The only reason an expression can complete abruptly is that an exception is thrown, because of either a <code>throw</code> with a given value <a href="statements.doc.html#237350">(§14.17)</a> or a run-time exception or error (<a href="exceptions.doc.html#44043">§11</a>, <a href="expressions.doc.html#79448">§15.6</a>).<p>
<a name="237118"></a>
If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.<p>
<a name="24642"></a>
Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.<p>
<a name="24647"></a>
Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.<p>
<a name="246838"></a>
<h2>14.2 Blocks</h2>
<a name="6391"></a>
A <em>block</em> is a sequence of statements, local class declarations and local variable declaration statements within braces.<p>
<ul><pre>
<em>Block:
{ BlockStatements<sub><i>opt</i></sub> }
BlockStatements:
BlockStatement
BlockStatements BlockStatement
BlockStatement:
LocalVariableDeclarationStatement
ClassDeclaration
Statement
</em></pre></ul><a name="5918"></a>
A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.<p>
<a name="247766"></a>
<h2>14.3 Local Class Declarations</h2>
<a name="247773"></a>
A local class is a nested class <a href="classes.doc.html#3857">(§8)</a> that is not a member of any class and that has a name. All local classes are inner classes <a href="classes.doc.html#262890">(§8.1.2)</a>. Every local class declaration statement is immediately contained by a block. Local class declaration statements may be intermixed freely with other kinds of statements in the block.<p>
<a name="257083"></a>
The scope of a local class declared in a block is the rest of the immediately enclosing block, including its own class declaration.<p>
<a name="247735"></a>
The name of a local class <i>C</i> may not be redeclared as a local class of the directly enclosing method, constructor, or initializer block within the scope of <i>C</i>, or a compile-time error occurs. However, a local class declaration may be shadowed <a href="names.doc.html#34133">(§6.3.1)</a> anywhere inside a class declaration nested within the local class declaration's scope. A local class does not have a canonical name, nor does it have a fully qualified name. <p>
<a name="247589"></a>
It is a compile-time error if a local class declaration contains any one of the following access modifiers: <code>public</code>, <code>protected</code>, <code>private, </code>or <code>static</code>.<p>
<a name="253218"></a>
Here is an example that illustrates several aspects of the rules given above:<p>
<blockquote><pre>class Global {
class Cyclic {}
void foo() {
new Cyclic(); // create a Global.Cyclic
class Cyclic extends Cyclic{}; // circular definition
{
class Local{};
{
class Local{}; // compile-time error
}
class Local{}; // compile-time error
class AnotherLocal {
void bar() {
class Local {}; // ok
}
}
}
class Local{}; // ok, not in scope of prior Local
}
</pre></blockquote><a name="249828"></a>
The first statement of method foo creates an instance of the member class <code>Global.Cyclic</code> rather than an instance of the local class <code>Cyclic</code>, because the local class declaration is not yet in scope. <p>
<a name="249848"></a>
The fact that the scope of a local class encompasses its own declaration (not only its body) means that the definition of the local class <code>Cyclic</code> is indeed cyclic because it extends itself rather than <code>Global.Cyclic</code>. Consequently, the declaration of the local class <code>Cyclic</code> will be rejected at compile time. <p>
<a name="249829"></a>
Since local class names cannot be redeclared within the same method (or constructor or initializer, as the case may be), the second and third declarations of <code>Local</code> result in compile-time errors. However, <code>Local</code> can be redeclared in the context of another, more deeply nested, class such as <code>AnotherLocal</code>. <p>
<a name="249872"></a>
The fourth and last declaration of <code>Local</code> is legal, since it occurs outside the scope of any prior declaration of <code>Local</code>.<p>
<a name="5920"></a>
<h2>14.4 Local Variable Declaration Statements</h2>
<a name="25561"></a>
A <em>local variable declaration statement</em> declares one or more local variable names.<p>
<ul><pre>
<em>LocalVariableDeclarationStatement:
LocalVariableDeclaration ;
LocalVariableDeclaration:
</em>final<em><sub>opt</sub> Type VariableDeclarators
</em></pre></ul><a name="238231"></a>
The following are repeated from <a href="classes.doc.html#40898">§8.3</a> to make the presentation here clearer:<p>
<ul><pre>
<em>VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator
VariableDeclarator:
VariableDeclaratorId
VariableDeclaratorId = VariableInitializer
VariableDeclaratorId:
Identifier
VariableDeclaratorId </em>[ ]<em>
VariableInitializer:
Expression
ArrayInitializer
</em></pre></ul><a name="32641"></a>
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.<p>
<a name="35375"></a>
A local variable declaration can also appear in the header of a <code>for</code> statement <a href="statements.doc.html#24588">(§14.13)</a>. In this case it is executed in the same manner as if it were part of a local variable declaration statement.<p>
<a name="35393"></a>
<h3>14.4.1 Local Variable Declarators and Types</h3>
<a name="35391"></a>
Each <em>declarator</em> in a local variable declaration declares one local variable, whose name is the <em>Identifier</em> that appears in the declarator.<p>
<a name="255532"></a>
If the optional keyword final appears at the start of the declarator, the variable being declared is a final variable<a href="typesValues.doc.html#10931">(§4.5.4)</a>.<p>
<a name="35396"></a>
The type of the variable is denoted by the <em>Type</em> that appears in the local variable declaration, followed by any bracket pairs that follow the <em>Identifier</em> in the declarator. <p>
<a name="252173"></a>
Thus, the local variable declaration:<p>
<blockquote><pre>int a, b[], c[][];
</pre></blockquote><a name="35401"></a>
is equivalent to the series of declarations:<p>
<blockquote><pre>int a;
int[] b;
int[][] c;
</pre></blockquote><a name="35405"></a>
Brackets are allowed in declarators as a nod to the tradition of C and C++. The general rule, however, also means that the local variable declaration:<p>
<blockquote><pre>float[][] f[][], g[][][], h[]; // Yechh!
</pre></blockquote><a name="35409"></a>
is equivalent to the series of declarations:<p>
<blockquote><pre>float[][][][] f;
float[][][][][] g;
float[][][] h;
</pre></blockquote><a name="35427"></a>
We do not recommend such "mixed notation" for array declarations.<p>
<a name="247538"></a>
A local variable of type <code>float</code> always contains a value that is an element of the float value set <a href="typesValues.doc.html#9208">(§4.2.3)</a>; similarly, a local variable of type <code>double</code> always contains a value that is an element of the double value set. It is not permitted for a local variable of type <code>float</code> 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 <code>double</code> to contain an element of the double-extended-exponent value set that is not also an element of the double value set.<p>
<a name="32644"></a>
<h3>14.4.2 Scope of Local Variable Declarations</h3>
<a name="257091"></a>
The scope of a local variable declaration in a block <a href="statements.doc.html#32644">(§14.4.2)</a> is the rest of the block in which the declaration appears, starting with its own initializer <a href="statements.doc.html#5920">(§14.4)</a> and including any further declarators to the right in the local variable declaration statement. <p>
<a name="248105"></a>
The name of a local variable <em>v</em> may not be redeclared as a local variable of the directly enclosing method, constructor or initializer block within the scope of <em>v</em>, or a compile-time error occurs. The name of a local variable <em>v</em> may not be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method, constructor or initializer block within the scope of <em>v</em>, or a compile-time error occurs. However, a local variable of a method or initializer block may be shadowed <a href="names.doc.html#34133">(§6.3.1)</a> anywhere inside a class declaration nested within the scope of the local variable. <p>
<a name="253395"></a>
A local variable cannot be referred to using a qualified name <a href="names.doc.html#104285">(§6.6)</a>, only a simple name.<p>
<a name="253396"></a>
The example:<p>
<blockquote><pre>class Test {
static int x;
public static void main(String[] args) {
int x = x;
}
}
</pre></blockquote><a name="32604"></a>
causes a compile-time error because the initialization of <code>x</code> is within the scope of the declaration of <code>x</code> as a local variable, and the local <code>x</code> does not yet have a value and cannot be used.<p>
<a name="32610"></a>
The following program does compile:<p>
<blockquote><pre>class Test {
static int x;
public static void main(String[] args) {
int x = (x=2)*2;
System.out.println(x);
}
}
</pre></blockquote><a name="32611"></a>
because the local variable <code>x</code> is definitely assigned <a href="defAssign.doc.html#25979">(§16)</a> before it is used. It prints:<p>
<blockquote><pre>4
<a name="5925"></a>
Here is another example:<p>
class Test {
public static void main(String[] args) {
System.out.print("2+1=");
int two = 2, three = two + 1;
System.out.println(three);
}
}
</pre></blockquote><a name="17863"></a>
which compiles correctly and produces the output:<p>
<blockquote><pre>2+1=3
</pre></blockquote><a name="7616"></a>
The initializer for <code>three</code> can correctly refer to the variable <code>two</code> declared in an earlier declarator, and the method invocation in the next line can correctly refer to the variable <code>three</code> declared earlier in the block.<p>
<a name="35349"></a>
The scope of a local variable declared in a <code>for</code> statement is the rest of the <code>for</code> statement, including its own initializer.<p>
<a name="32558"></a>
If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.<p>
<a name="252192"></a>
Thus the following example does not compile:<p>
<blockquote><pre>class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
</pre></blockquote>
<a name="249885"></a>
This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. Hence, the following example compiles without error:<p>
<blockquote><pre>
class Test {
public static void main(String[] args) {
int i;
class Local {
{
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
new Local();
}
}
</pre></blockquote>
<a name="35322"></a>
On the other hand, local variables with the same name may be declared in two separate blocks or <code>for</code> statements neither of which contains the other. Thus:<p>
<blockquote><pre>
class Test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.print(i + " ");
for (int i = 10; i > 0; i--)
System.out.print(i + " ");
System.out.println();
}
}
</pre></blockquote><a name="17897"></a>
compiles without error and, when executed, produces the output:<p>
<blockquote><pre>0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
</pre></blockquote><a name="32673"></a>
<h3>14.4.3 Shadowing of Names by Local Variables</h3>
<a name="32716"></a>
If a name declared as a local variable is already declared as a field name, then that outer declaration is shadowed <a href="names.doc.html#34133">(§6.3.1)</a> throughout the scope of the local variable. Similarly, if a name is already declared as a variable or parameter name, then that outer declaration is shadowed throughout the scope of the local variable (provided that the shadowing does not cause a compile-time error under the rules of <a href="statements.doc.html#32644">§14.4.2</a>). The shadowed name can sometimes be accessed using an appropriately qualified name. <p>
<a name="252205"></a>
For example, the keyword <code>this</code> can be used to access a shadowed field <code>x</code>, using the form <code>this.x</code>. Indeed, this idiom typically appears in constructors <a href="classes.doc.html#41652">(§8.8)</a>:<p>
<blockquote><pre>class Pair {
Object first, second;
public Pair(Object first, Object second) {
this.first = first;
this.second = second;
}
}
</pre></blockquote><a name="32573"></a>
In this example, the constructor takes parameters having the same names as the fields to be initialized. This is simpler than having to invent different names for the parameters and is not too confusing in this stylized context. In general, however, it is considered poor style to have local variables with the same names as fields.<p>
<a name="32717"></a>
<h3>14.4.4 Execution of Local Variable Declarations</h3>
<a name="32574"></a>
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 initialization expression, the expression is evaluated and its value is assigned to the variable. If a declarator does not have an initialization expression, then a Java compiler must prove, using exactly the algorithm given in <a href="defAssign.doc.html#25979">§16</a>, that every reference to the variable is necessarily preceded by execution of an assignment to the variable. If this is not the case, then a compile-time error occurs.<p>
<a name="32578"></a>
Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.<p>
<a name="32584"></a>
<h2>14.5 Statements</h2>
<a name="32588"></a>
There are many kinds of statements in the Java programming language. Most correspond to statements in the C and C++ languages, but some are unique.<p>
<a name="5958"></a>
As in C and C++, the <code>if</code> statement of the Java programming language suffers from the so-called "dangling <code>else</code> problem," illustrated by this misleadingly formatted example:<p>
<pre><a name="17933"></a>
if (door.isOpen())
<a name="5960"></a> if (resident.isVisible())
<a name="35428"></a> resident.greet("Hello!");
<a name="5961"></a>else door.bell.ring(); // A "dangling else"
</pre><a name="5962"></a>
The problem is that both the outer <code>if</code> statement and the inner <code>if</code> statement might conceivably own the <code>else</code> clause. In this example, one might surmise that the programmer intended the <code>else</code> clause to belong to the outer <code>if</code> statement. The Java programming language, like C and C++ and many programming languages before them, arbitrarily decree that an <code>else</code> clause belongs to the innermost <code>if</code> to which it might possibly belong. This rule is captured by the following grammar:<p>
<ul><pre>
<em>Statement:
StatementWithoutTrailingSubstatement
LabeledStatement
IfThenStatement
IfThenElseStatement
WhileStatement
ForStatement
StatementWithoutTrailingSubstatement:
Block
EmptyStatement
ExpressionStatement
SwitchStatement
DoStatement
BreakStatement
ContinueStatement
ReturnStatement
SynchronizedStatement
ThrowStatement
TryStatement
StatementNoShortIf:
StatementWithoutTrailingSubstatement
LabeledStatementNoShortIf
IfThenElseStatementNoShortIf
WhileStatementNoShortIf
ForStatementNoShortIf
</em></pre></ul><a name="8344"></a>
The following are repeated from <a href="statements.doc.html#5991">§14.9</a> to make the presentation here clearer:<p>
<ul><pre>
<em>IfThenStatement:
</em>if<em> ( Expression ) Statement
IfThenElseStatement:
</em>if<em> ( Expression ) StatementNoShortIf </em>else<em> Statement
IfThenElseStatementNoShortIf:
</em>if<em> ( Expression ) StatementNoShortIf </em>else<em> StatementNoShortIf
</em></pre></ul><a name="5969"></a>
Statements are thus grammatically divided into two categories: those that might end in an <code>if</code> statement that has no <code>else</code> clause (a "short <code>if</code> statement") and those that definitely do not. Only statements that definitely do not end in a short <code>if</code> statement may appear as an immediate substatement before the keyword <code>else</code> in an <code>if</code> statement that does have an <code>else</code> clause.<p>
<a name="252213"></a>
This simple rule prevents the "dangling <code>else</code>" problem. The execution behavior of a statement with the "no short <code>if</code>" restriction is identical to the execution behavior of the same kind of statement without the "no short <code>if</code>" restriction; the distinction is drawn purely to resolve the syntactic difficulty.<p>
<a name="5970"></a>
<h2>14.6 The Empty Statement</h2>
<a name="5971"></a>
An <em>empty statement</em> does nothing.<p>
<ul><pre>
<em>EmptyStatement:
;
</em></pre></ul><a name="5973"></a>
Execution of an empty statement always completes normally.<p>
<a name="78993"></a>
<h2>14.7 Labeled Statements</h2>
<a name="78994"></a>
Statements may have <em>label</em> prefixes.<p>
<ul><pre>
<em>LabeledStatement:
Identifier : Statement
LabeledStatementNoShortIf:
Identifier : StatementNoShortIf
</em></pre></ul><a name="78997"></a>
The <em>Identifier</em> is declared to be the label of the immediately contained <em>Statement</em>.<p>
<a name="17941"></a>
Unlike C and C++, the Java programming language has no <code>goto</code> statement; identifier statement labels are used with <code>break</code> <a href="statements.doc.html#6842">(§14.14)</a> or <code>continue</code> <a href="statements.doc.html#6122">(§14.15)</a> statements appearing anywhere within the labeled statement.<p>
<a name="257102"></a>
The scope of a label declared by a labeled statement is the statement immediately enclosed by the labeled statement.<p>
<a name="78998"></a>
Let <i>l</i> be a label, and let <i>m</i> be the immediately enclosing method, constructor, instance initializer or static initializer. It is a compile-time error if <i>l</i> shadows <a href="names.doc.html#34133">(§6.3.1)</a> the declaration of another label immediately enclosed in <i>m</i>.<p>
<a name="247865"></a>
There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not obscure <a href="names.doc.html#104058">(§6.3.2)</a> a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier  as a class, interface, method, field, local variable or as the parameter of an exception handler <a href="statements.doc.html#79311">(§14.19)</a> does not obscure a statement label with the same name.<p>
<a name="247869"></a>
A labeled statement is executed by executing the immediately contained <em>Statement</em>. If the statement is labeled by an <em>Identifier</em> and the contained <em>Statement</em> completes abruptly because of a <code>break</code> with the same <em>Identifier</em>, then the labeled statement completes normally. In all other cases of abrupt completion of the <em>Statement</em>,  the labeled statement completes abruptly for the same reason.<p>
<a name="5984"></a>
<h2>14.8 Expression Statements</h2>
<a name="5985"></a>
Certain kinds of expressions may be used as statements by following them with semicolons:<p>
<ul><pre>
<em>ExpressionStatement:
StatementExpression ;
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
</em></pre></ul><a name="5988"></a>
An <em>expression statement</em> is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.<p>
<a name="5989"></a>
Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a "cast to <code>void</code>"-<code>void</code> is not a type-so the traditional C trick of writing an expression statement such as:<p>
<blockquote><pre>(void) ... ; // incorrect!
</pre></blockquote><a name="35457"></a>
does not work. On the other hand, the language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a <code>void</code> method, so such a trick is almost never needed. If a trick is needed, either an assignment statement <a href="expressions.doc.html#5281">(§15.26)</a> or a local variable declaration statement <a href="statements.doc.html#5920">(§14.4)</a> can be used instead.<p>
<a name="5991"></a>
<h2>14.9 The <code>if</code> Statement</h2>
<a name="35469"></a>
The <code>if</code> statement allows conditional execution of a statement or a conditional choice of two statements, executing one or the other but not both.<p>
<ul><pre>
<em>IfThenStatement:
</em>if<em> ( Expression ) Statement
IfThenElseStatement:
</em>if<em> ( Expression ) StatementNoShortIf </em>else<em> Statement
IfThenElseStatementNoShortIf:
</em>if<em> ( Expression ) StatementNoShortIf </em>else<em> StatementNoShortIf
</em></pre></ul><a name="24313"></a>
The <em>Expression</em> must have type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="237433"></a>
<h3>14.9.1 The <code>if-then</code> Statement</h3>
<a name="35473"></a>
An <code>if</code>-<code>then</code> statement is executed by first evaluating the <em>Expression</em>. If evaluation of the <em>Expression</em> completes abruptly for some reason, the <code>if</code>-<code>then</code> statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:<p>
<ul><a name="5997"></a>
<li>If the value is <code>true</code>, then the contained <em>Statement</em> is executed; the <code>if</code>-<code>then</code> statement completes normally if and only if execution of the <em>Statement</em> completes normally.
<a name="5998"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>if</code>-<code>then</code> statement completes normally.
</ul><a name="237435"></a>
<h3>14.9.2 The <code>if-then-else</code> Statement</h3>
<a name="236506"></a>
An <code>if</code>-<code>then</code>-<code>else</code> statement is executed by first evaluating the <em>Expression</em>. If evaluation of the <em>Expression</em> completes abruptly for some reason, then the <code>if</code>-<code>then</code>-<code>else</code>  statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:<p>
<ul><a name="6000"></a>
<li>If the value is <code>true</code>, then the first contained <em>Statement</em> (the one before the <code>else</code> keyword) is executed; the <code>if</code>-<code>then</code>-<code>else</code> statement completes normally if and only if execution of that statement completes normally.
<a name="42708"></a>
<li>If the value is <code>false</code>, then the second contained <em>Statement</em> (the one after the <code>else</code> keyword) is executed; the <code>if</code>-<code>then</code>-<code>else</code> statement completes normally if and only if execution of that statement completes normally.
</ul><a name="35518"></a>
<h2>14.10 The <code>switch</code> Statement</h2>
<a name="35522"></a>
The <code>switch</code> statement transfers control to one of several statements depending on the value of an expression.<p>
<ul><pre>
<em>SwitchStatement:
</em> switch<em> ( Expression ) SwitchBlock
SwitchBlock:
{ SwitchBlockStatementGroups<sub><i>opt</i></sub> SwitchLabels<sub><i>opt</i></sub> }
SwitchBlockStatementGroups:
SwitchBlockStatementGroup
SwitchBlockStatementGroups SwitchBlockStatementGroup
SwitchBlockStatementGroup:
SwitchLabels BlockStatements
SwitchLabels:
SwitchLabel
SwitchLabels SwitchLabel
SwitchLabel:
</em>case<em> ConstantExpression :
default :
</em></pre></ul><a name="256918"></a>
The type of the <em>Expression</em> must be <code>char</code>, <code>byte</code>, <code>short</code>, or <code>int</code>, or a compile-time error occurs.<p>
<a name="256924"></a>
The body of a <code>switch</code> statement is known as a <em>switch block</em>. Any statement immediately contained by the switch block may be labeled with one or more <code>case</code> or <code>default</code> labels. These labels are said to be <em>associated</em> with the <code>switch</code> statement, as are the values of the constant expressions <a href="expressions.doc.html#5313">(§15.28)</a> in the <code>case</code> labels.<p>
<a name="237328"></a>
All of the following must be true, or a compile-time error will result:<p>
<ul><a name="237329"></a>
<li>Every <code>case</code> constant expression associated with a <code>switch</code> statement must be assignable <a href="conversions.doc.html#184206">(§5.2)</a> to the type of the <code>switch</code> <em>Expression</em>.
<a name="237333"></a>
<li>No two of the <code>case</code> constant expressions associated with a <code>switch</code> statement may have the same value.
<a name="237334"></a>
<li>At most one <code>default</code> label may be associated with the same <code>switch</code> statement.
<a name="252239"></a>
In C and C++ the body of a <code>switch</code> statement can be a statement and statements with <code>case</code> labels do not have to be immediately contained by that statement. Consider the simple loop:<p>
</ul><blockquote><pre>for (i = 0; i < n; ++i) foo();
</pre></blockquote><a name="237282"></a>
where <code>n</code> is known to be positive. A trick known as <em>Duff's device</em> can be used in C or C++ to unroll the loop, but this is not valid code in the Java programming language:<p>
<blockquote><pre>int q = (n+7)/8;
switch (n%8) {
case 0: do { foo(); // Great C hack, Tom,
case 7: foo(); // but it's not valid here.
case 6: foo();
case 5: foo();
case 4: foo();
case 3: foo();
case 2: foo();
case 1 foo();
} while (--q >= 0);
}
</pre></blockquote><a name="237295"></a>
Fortunately, this trick does not seem to be widely known or used. Moreover, it is less needed nowadays; this sort of code transformation is properly in the province of state-of-the-art optimizing compilers.<p>
<a name="217138"></a>
When the <code>switch</code> statement is executed, first the <em>Expression</em> is evaluated. If evaluation of the <em>Expression</em> completes abruptly for some reason, the <code>switch</code> statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the <em>Expression </em>with each <code>case</code> constant. Then there is a choice:<p>
<ul><a name="6012"></a>
<li>If one of the <code>case</code> constants is equal to the value of the expression, then we say that the <code>case</code> matches, and all statements after the matching <code>case</code> label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the matching <code>case</code> label, then the entire <code>switch</code> statement completes normally.
<a name="6013"></a>
<li>If no <code>case</code> matches but there is a <code>default</code> label, then all statements after the matching <code>default</code> label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the <code>default</code> label, then the entire <code>switch</code> statement completes normally.
<a name="6014"></a>
<li>If no <code>case</code> matches and there is no <code>default</code> label, then no further action is taken and the <code>switch</code> statement completes normally.
</ul><a name="237254"></a>
If any statement immediately contained by the <em>Block</em> body of the <code>switch</code> statement completes abruptly, it is handled as follows:<p>
<ul><a name="6017"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>switch</code> statement completes normally.
<a name="237272"></a>
<li>If execution of the <em>Statement</em> completes abruptly for any other reason, the <code>switch</code> statement completes abruptly for the same reason. The case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="statements.doc.html#78993">(§14.7)</a>.
</ul><a name="237607"></a>
As in C and C++, execution of statements in a switch block "falls through labels." <p>
<a name="252252"></a>
For example, the program:<p>
<blockquote><pre>class Toomany {
static void howMany(int k) {
switch (k) {
case 1: System.out.print("one ");
case 2: System.out.print("too ");
case 3: System.out.println("many");
}
}
public static void main(String[] args) {
howMany(3);
howMany(2);
howMany(1);
}
}
</pre></blockquote><a name="237629"></a>
contains a switch block in which the code for each case falls through into the code for the next case. As a result, the program prints:<p>
<blockquote><pre>many
too many
one too many
</pre></blockquote><a name="237630"></a>
If code is not to fall through case to case in this manner, then <code>break</code> statements should be used, as in this example:<p>
<blockquote><pre>class Twomany {
static void howMany(int k) {
switch (k) {
case 1: System.out.println("one");
break; // exit the switch
case 2: System.out.println("two");
break; // exit the switch
case 3: System.out.println("many");
break; // not needed, but good style
}
}
public static void main(String[] args) {
howMany(1);
howMany(2);
howMany(3);
}
}
</pre></blockquote><a name="237642"></a>
This program prints:<p>
<blockquote><pre>one
two
many
</pre></blockquote><a name="237277"></a>
<h2>14.11 The while Statement</h2>
<a name="237278"></a>
The <code>while</code> statement executes an <em>Expression</em> and a <em>Statement</em> repeatedly until the value of the <em>Expression</em> is <code>false</code>.<p>
<ul><pre>
WhileStatement:
while ( Expression ) Statement
WhileStatementNoShortIf:
while ( Expression ) StatementNoShortIf
</pre></ul><a name="35485"></a>
The <em>Expression</em> must have type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="217153"></a>
A <code>while</code> statement is executed by first evaluating the <em>Expression</em>. If evaluation of the <em>Expression</em> completes abruptly for some reason, the <code>while</code> statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:<p>
<ul><a name="6028"></a>
<li>If the value is <code>true</code>, then the contained <em>Statement</em> is executed. Then there is a choice:
<ul>
<a name="6029"></a>
<li>If execution of the <em>Statement</em> completes normally, then the entire <code>while</code> statement is executed again, beginning by re-evaluating the <em>Expression</em>.
<a name="6030"></a>
<li>If execution of the <em>Statement</em> completes abruptly, see <a href="statements.doc.html#21139">§14.11.1</a> below.
</ul>
<a name="6031"></a>
<li>If the value of the <em>Expression</em> is <code>false</code>, no further action is taken and the <code>while</code> statement completes normally.
</ul><a name="6032"></a>
If the value of the <em>Expression</em> is <code>false</code> the first time it is evaluated, then the <em>Statement</em>  is not executed.<p>
<a name="21139"></a>
<h3>14.11.1 Abrupt Completion</h3>
<a name="6033"></a>
Abrupt completion of the contained <em>Statement</em> is handled in the following manner:<p>
<ul><a name="6034"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>while</code> statement completes normally.
<ul>
<a name="6035"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with no label, then the entire <code>while</code> statement is executed again.
<a name="79063"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79064"></a>
<li>If the <code>while</code> statement has label <i>L</i>, then the entire <code>while</code> statement is executed again.
<a name="79065"></a>
<li>If the <code>while</code> statement does not have label <i>L</i>, the <code>while</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="79070"></a>
<li>If execution of the <em>Statement</em> completes abruptly for any other reason, the <code>while</code> statement completes abruptly for the same reason. Note that the case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="statements.doc.html#78993">(§14.7)</a>.
</ul>
</ul><a name="6045"></a>
<h2>14.12 The do Statement</h2>
<a name="246911"></a>
The <code>do</code> statement executes a <em>Statement</em> and an <em>Expression</em> repeatedly until the value of the <em>Expression</em> is <code>false</code>.<p>
<ul><pre>
DoStatement:
do Statement while ( Expression ) ;
</pre></ul><a name="35496"></a>
The <em>Expression</em> must have type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="6048"></a>
A <code>do</code> statement is executed by first executing the <em>Statement</em>. Then there is a choice:<p>
<ul><a name="217176"></a>
<li>If execution of the <em>Statement</em> completes normally, then the <em>Expression</em> is evaluated. If evaluation of the <em>Expression</em> completes abruptly for some reason, the <code>do</code> statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value:
<ul>
<a name="217172"></a>
<li>If the value is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="6051"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="6052"></a>
<li>If execution of the <em>Statement</em> completes abruptly, see <a href="statements.doc.html#45366">§14.12.1</a> below.
</ul><a name="6053"></a>
Executing a <code>do</code> statement always executes the contained <em>Statement</em> at least once.<p>
<a name="45366"></a>
<h3>14.12.1 Abrupt Completion</h3>
<a name="43246"></a>
Abrupt completion of the contained <em>Statement</em> is handled in the following manner:<p>
<ul><a name="6714"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>break</code> with no label, then no further action is taken and the <code>do</code> statement completes normally.
<a name="6056"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with no label, then the <em>Expression</em> is evaluated. Then there is a choice based on the resulting value:
<ul>
<a name="6057"></a>
<li>If the value is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="6058"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="79109"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79110"></a>
<li>If the <code>do</code> statement has label <i>L</i>, then the <em>Expression</em> is evaluated. Then there is a choice:
<ul>
<a name="79111"></a>
<li>If the value of the <em>Expression</em> is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="79112"></a>
<li>If the value of the <em>Expression</em> is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="79113"></a>
<li>If the <code>do</code> statement does not have label <i>L</i>, the <code>do</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="24581"></a>
<li>If execution of the <em>Statement</em> completes abruptly for any other reason, the <code>do</code> statement completes abruptly for the same reason. The case of abrupt completion because of a <code>break</code> with a label is handled by the general rule <a href="statements.doc.html#78993">(§14.7)</a>.
</ul><a name="24585"></a>
<h3>14.12.2 Example of do statement</h3>
<a name="252264"></a>
The following code is one possible implementation of the <code>toHexString</code> method of class <code>Integer</code>:<p>
<blockquote><pre>public static String toHexString(int i) {
StringBuffer buf = new StringBuffer(8);
do {
buf.append(Character.forDigit(i & 0xF, 16));
i >>>= 4;
} while (i != 0);
return buf.reverse().toString();
}
</pre></blockquote><a name="24586"></a>
Because at least one digit must be generated, the <code>do</code> statement is an appropriate control structure.<p>
<a name="24588"></a>
<h2>14.13 The <code>for</code> Statement</h2>
<a name="35537"></a>
The <code>for</code> statement executes some initialization code, then executes an <em>Expression</em>, a <em>Statement</em>, and some update code repeatedly until the value of the <em>Expression</em> is <code>false</code>.<p>
<ul><pre>
<em>ForStatement:
</em>for<em> ( ForInit<sub><i>opt</i></sub> ; Expression<sub><i>opt</i></sub> ; ForUpdate<sub><i>opt</i></sub> )
Statement
ForStatementNoShortIf:
</em>for<em> ( ForInit<sub><i>opt</i></sub> ; Expression<sub><i>opt</i></sub> ; ForUpdate<sub><i>opt</i></sub> )
StatementNoShortIf
ForInit:
StatementExpressionList
LocalVariableDeclaration
ForUpdate:
StatementExpressionList
StatementExpressionList:
StatementExpression
StatementExpressionList , StatementExpression
</em></pre></ul><a name="35529"></a>
The <em>Expression</em> must have type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="45367"></a>
<h3>14.13.1 Initialization of <code>for</code> statement</h3>
<a name="11751"></a>
A <code>for</code> statement is executed by first executing the <em>ForInit</em> code:<p>
<ul><a name="6081"></a>
<li>If the <em>ForInit</em> code is a list of statement expressions <a href="statements.doc.html#5984">(§14.8)</a>, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the <code>for</code> statement completes abruptly for the same reason; any <em>ForInit</em> statement expressions to the right of the one that completed abruptly are not evaluated.
</ul><a name="257107"></a>
If the <em>ForInit</em> code is a local variable declaration, it is executed as if it were a local variable declaration statement <a href="statements.doc.html#5920">(§14.4)</a> appearing in a block. The scope of a local variable declared in the <em>ForInit</em> part of a <code>for</code> statement <a href="statements.doc.html#24588">(§14.13)</a> includes all of the following:<p>
<ul><a name="257112"></a>
<li>Its own initializer
<a name="257115"></a>
<li>Any further declarators to the right in the <em>ForInit</em> part of the <code>for</code> statement
<a name="257116"></a>
<li>The <em>Expression</em> and <em>ForUpdate</em> parts of the <code>for</code> statement
<a name="257117"></a>
<li>The contained <em>Statement</em>
</ul><a name="256793"></a>
If execution of the local variable declaration completes abruptly for any reason, the <code>for</code> statement completes abruptly for the same reason.<p>
<ul><a name="6083"></a>
<li>If the <em>ForInit</em> part is not present, no action is taken.
</ul><a name="45370"></a>
<h3>14.13.2 Iteration of for statement</h3>
<a name="217196"></a>
Next, a <code>for</code> iteration step is performed, as follows:<p>
<ul><a name="217202"></a>
<li>If the <em>Expression</em> is present, it is evaluated, and if evaluation of the <em>Expression</em> completes abruptly, the <code>for</code> statement completes abruptly for the same reason. Otherwise, there is then a choice based on the presence or absence of the <em>Expression</em> and the resulting value if the <em>Expression</em> is present:
<ul>
<a name="6086"></a>
<li>If the <em>Expression</em> is not present, or it is present and the value resulting from its evaluation is <code>true</code>, then the contained <em>Statement</em> is executed. Then there is a choice:
<ul>
<a name="6087"></a>
<li>If execution of the <em>Statement</em> completes normally, then the following two steps are performed in sequence:
<ul>
<a name="45351"></a>
<li>First, if the <em>ForUpdate</em> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the <code>for</code> statement completes abruptly for the same reason; any <em>ForUpdate</em> statement expressions to the right of the one that completed abruptly are not evaluated. If the <em>ForUpdate</em> part is not present, no action is taken.
<a name="236152"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="236156"></a>
<li>If execution of the <em>Statement</em> completes abruptly, see <a href="statements.doc.html#45371">§14.13.3</a> below.
</ul>
<a name="236157"></a>
<li>If the <em>Expression</em> is present and the value resulting from its evaluation is <code>false</code>, no further action is taken and the <code>for</code> statement completes normally.
</ul>
</ul><a name="6092"></a>
If the value of the <em>Expression</em> is <code>false</code> the first time it is evaluated, then the <em>Statement</em> is not executed.<p>
<a name="6093"></a>
If the <em>Expression</em> is not present, then the only way a <code>for</code> statement can complete normally is by use of a <code>break</code> statement.<p>
<a name="45371"></a>
<h3>14.13.3 Abrupt Completion of <code>for</code> statement</h3>
<a name="43248"></a>
Abrupt completion of the contained <em>Statement</em> is handled in the following manner:<p>
<ul><a name="6095"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>for</code> statement completes normally.
<a name="6096"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with no label, then the following two steps are performed in sequence:
<ul>
<a name="6097"></a>
<li>First, if the <em>ForUpdate</em> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the <em>ForUpdate</em>  part is not present, no action is taken.
<a name="6098"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="79161"></a>
<li>If execution of the <em>Statement</em> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79162"></a>
<li>If the <code>for</code> statement has label <i>L</i>, then the following two steps are performed in sequence:
<ul>
<a name="79163"></a>
<li>First, if the <em>ForUpdate</em> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the<em> ForUpdate</em> is not present, no action is taken.
<a name="79164"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="79165"></a>
<li>If the <code>for</code> statement does not have label <i>L</i>, the <code>for</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="6104"></a>
<li>If execution of the <em>Statement</em> completes abruptly for any other reason, the <code>for</code> statement completes abruptly for the same reason. Note that the case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="statements.doc.html#78993">(§14.7)</a>.
</ul><a name="6842"></a>
<h2>14.14 The <code>break</code> Statement</h2>
<a name="35540"></a>
A break statement transfers control out of an enclosing statement.<p>
<ul><pre>
<em>BreakStatement:
</em> break<em> Identifier<sub><i>opt</i></sub> ;
</em></pre></ul><a name="43392"></a>
A <code>break</code> statement with no label attempts to transfer control to the innermost enclosing <code>switch</code>, <code>while</code>, <code>do</code>, or <code>for</code> statement of the immediately enclosing method or initializer block; this statement, which is called the <em>break target</em>, then immediately completes normally. <p>
<a name="256041"></a>
To be precise, a <code>break</code> statement with no label always completes abruptly, the reason being a <code>break</code> with no label. If no <code>switch</code>, <code>while</code>, <code>do</code>, or <code>for</code> statement encloses the <code>break</code> statement, a compile-time error occurs.<p>
<a name="79188"></a>
A <code>break</code> statement with label <em>Identifier</em> attempts to transfer control to the enclosing labeled statement <a href="statements.doc.html#78993">(§14.7)</a> that has the same <em>Identifier</em> as its label; this statement, which is called the <em>break target</em>, then immediately completes normally. In this case, the <code>break</code> target need not be a <code>while</code>, <code>do</code>, <code>for</code>, or <code>switch</code> statement. A break statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.<p>
<a name="247471"></a>
To be precise, a <code>break</code> statement with label <em>Identifier</em> always completes abruptly, the reason being a <code>break</code> with label <em>Identifier</em>. If no labeled statement with <em>Identifier</em>  as its label encloses the <code>break</code> statement, a compile-time error occurs.<p>
<a name="43504"></a>
It can be seen, then, that a <code>break</code> statement always completes abruptly.<p>
<a name="43404"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="statements.doc.html#79311">(§14.19)</a> within the break target whose <code>try</code> blocks contain the <code>break</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>break</code> statement.<p>
<a name="18004"></a>
In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes <i>P</i> and <i>Q</i>, where <i>Q</i> may be the same as <i>P</i>, there is at most one edge from <i>P</i> to <i>Q</i>. Nodes are represented by integers, and there is an edge from node <i>i</i> to node <code>edges[</code><i>i</i><code>][</code><i>j</i><code>]</code> for every <i>i</i> and <i>j</i> for which the array reference <code>edges[</code><i>i</i><code>][</code><i>j</i><code>]</code> does not throw an <code>IndexOutOfBoundsException</code>.<p>
<a name="42801"></a>
The task of the method <code>loseEdges</code>, given integers <i>i</i> and <i>j</i>, is to construct a new graph by copying a given graph but omitting the edge from node <i>i</i> to node <i>j</i>, if any, and the edge from node <i>j</i> to node <i>i</i>, if any:<p>
<blockquote><pre>class Graph {
int edges[][];
public Graph(int[][] edges) { this.edges = edges; }
public Graph loseEdges(int i, int j) {
int n = edges.length;
int[][] newedges = new int[n][];
for (int k = 0; k < n; ++k) {
edgelist: {
int z;
search: {
if (k == i) {
for (z = 0; z < edges[k].length; ++z)
if (edges[k][z] == j)
break search;
} else if (k == j) {
for (z = 0; z < edges[k].length; ++z)
if (edges[k][z] == i)
break search;
}
// No edge to be deleted; share this list.
newedges[k] = edges[k];
break edgelist;
} //search
// Copy the list, omitting the edge at position z.
int m = edges[k].length - 1;
int ne[] = new int[m];
System.arraycopy(edges[k], 0, ne, 0, z);
System.arraycopy(edges[k], z+1, ne, z, m-z);
newedges[k] = ne;
} //edgelist
}
return new Graph(newedges);
}
}
</pre></blockquote><a name="42887"></a>
Note the use of two statement labels, <code>edgelist</code> and <code>search</code>, and the use of <code>break</code> statements. This allows the code that copies a list, omitting one edge, to be shared between two separate tests, the test for an edge from node <i>i</i> to node <i>j</i>, and the test for an edge from node <i>j</i> to node <i>i</i>.<p>
<a name="6122"></a>
<h2>14.15 The <code>continue</code> Statement</h2>
<a name="6123"></a>
A <code>continue</code> statement may occur only in a <code>while</code>, <code>do</code>, or <code>for</code> statement; statements of these three kinds are called <em>iteration statements</em>. Control passes to the loop-continuation point of an iteration statement.<p>
<ul><pre>
<em>ContinueStatement:
</em>continue<em> Identifier<sub><i>opt</i></sub> ;
</em></pre></ul><a name="6125"></a>
A <code>continue</code> statement with no label attempts to transfer control to the innermost enclosing <code>while</code>, <code>do</code>, or <code>for</code> statement of the immediately enclosing method or initializer block; this statement, which is called the <em>continue target</em>, then immediately ends the current iteration and begins a new one. <p>
<a name="256040"></a>
To be precise, such a <code>continue</code> statement always completes abruptly, the reason being a <code>continue</code> with no label. If no <code>while</code>, <code>do</code>, or <code>for</code> statement of the immediately enclosing method or initializer block encloses the <code>continue</code> statement, a compile-time error occurs.<p>
<a name="247489"></a>
A <code>continue</code> statement with label <em>Identifier</em> attempts to transfer control to the enclosing labeled statement <a href="statements.doc.html#78993">(§14.7)</a> that has the same <em>Identifier</em> as its label; that statement, which is called the <em>continue target</em>, then immediately ends the current iteration and begins a new one. The continue target must be a <code>while</code>, <code>do</code>, or <code>for</code> statement or a compile-time error occurs. A continue statement must refer to a label within the immediately enclosing method or initializer block. There are no non-local jumps.<p>
<a name="79215"></a>
More precisely, a <code>continue</code> statement with label <em>Identifier</em> always completes abruptly, the reason being a <code>continue</code> with label <em>Identifier</em>. If no labeled statement with <em>Identifier</em> as its label contains the <code>continue</code> statement, a compile-time error occurs.<p>
<a name="43498"></a>
It can be seen, then, that a <code>continue</code> statement always completes abruptly.<p>
<a name="6136"></a>
See the descriptions of the <code>while</code> statement <a href="statements.doc.html#237277">(§14.11)</a>, <code>do</code> statement <a href="statements.doc.html#6045">(§14.12)</a>, and <code>for</code> statement <a href="statements.doc.html#24588">(§14.13)</a> for a discussion of the handling of abrupt termination because of <code>continue</code>.<p>
<a name="252288"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="statements.doc.html#79311">(§14.19)</a> within the continue target whose <code>try</code> blocks contain the <code>continue</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>continue</code> statement.<p>
<a name="42935"></a>
In the <code>Graph</code> example in the preceding section, one of the <code>break</code> statements is used to finish execution of the entire body of the outermost <code>for</code> loop. This <code>break</code> can be replaced by a <code>continue</code> if the <code>for</code> loop itself is labeled:<p>
<blockquote><pre>class Graph {
. . .
public Graph loseEdges(int i, int j) {
int n = edges.length;
int[][] newedges = new int[n][];
edgelists: for (int k = 0; k < n; ++k) {
int z;
search: {
if (k == i) {
. . .
} else if (k == j) {
. . .
}
newedges[k] = edges[k];
continue edgelists;
} // search
. . .
} // edgelists
return new Graph(newedges);
}
}
</pre></blockquote><a name="42984"></a>
Which to use, if either, is largely a matter of programming style.<p>
<a name="6767"></a>
<h2>14.16 The <code>return</code> Statement</h2>
<a name="124158"></a>
A <code>return</code> statement returns control to the invoker of a method (<a href="classes.doc.html#40420">§8.4</a>, <a href="expressions.doc.html#20448">§15.12</a>) or constructor (<a href="classes.doc.html#41652">§8.8</a>, <a href="expressions.doc.html#41147">§15.9</a>).<p>
<ul><pre>
<em>ReturnStatement:
</em>return<em> Expression<sub><i>opt</i></sub> ;
</em></pre></ul><a name="236030"></a>
A <code>return</code> statement with no <em>Expression </em>must be contained in the body of a method that is declared, using the keyword <code>void</code>, not to return any value <a href="classes.doc.html#40420">(§8.4)</a>, or in the body of a constructor <a href="classes.doc.html#41652">(§8.8)</a>. A compile-time error occurs if a <code>return</code> statement appears within an instance initializer or a static initializer <a href="classes.doc.html#39245">(§8.7)</a>. A <code>return</code> statement with no <em>Expression</em> attempts to transfer control to the invoker of the method or constructor that contains it. <p>
<a name="256046"></a>
To be precise, a <code>return</code> statement with no <em>Expression</em> always completes abruptly, the reason being a <code>return</code> with no value.<p>
<a name="6148"></a>
A <code>return</code> statement with an <em>Expression</em> must be contained in a method declaration that is declared to return a value <a href="classes.doc.html#40420">(§8.4)</a> or a compile-time error occurs. The <em>Expression</em> must denote a variable or value of some type <i>T</i>, or a compile-time error occurs. The type <i>T</i> must be assignable <a href="conversions.doc.html#184206">(§5.2)</a> to the declared result type of the method, or a compile-time error occurs.<p>
<a name="247542"></a>
A <code>return</code> statement with an <em>Expression</em> attempts to transfer control to the invoker of the method that contains it; the value of the <em>Expression</em> becomes the value of the method invocation. More precisely, execution of such a <code>return</code> statement first evaluates the <em>Expression</em>. If the evaluation of the <em>Expression</em> completes abruptly for some reason, then the <code>return</code> statement completes abruptly for that reason. If evaluation of the <em>Expression</em> completes normally, producing a value <i>V</i>, then the <code>return</code> statement completes abruptly, the reason being a <code>return</code> with value <i>V</i>. If the expression is of type <code>float</code> and is not FP-strict <a href="expressions.doc.html#249198">(§15.4)</a>, then the value may be an element of either the float value set or the float-extended-exponent value set <a href="typesValues.doc.html#9208">(§4.2.3)</a>. If the expression is of type <code>double</code> and is not FP-strict, then the value may be an element of either the double value set or the double-extended-exponent value set.<p>
<a name="43495"></a>
It can be seen, then, that a <code>return</code> statement always completes abruptly.<p>
<a name="43508"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="statements.doc.html#79311">(§14.19)</a> within the method or constructor whose <code>try</code> blocks contain the <code>return</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>return</code> statement.<p>
<a name="237350"></a>
<h2>14.17 The <code>throw</code> Statement</h2>
<a name="79254"></a>
A <code>throw</code> statement causes an exception <a href="exceptions.doc.html#44043">(§11)</a> to be thrown. The result is an immediate transfer of control <a href="exceptions.doc.html#44153">(§11.3)</a> that may exit multiple statements and multiple constructor, instance initializer, static initializer and field initializer evaluations, and method invocations until a <code>try</code> statement <a href="statements.doc.html#79311">(§14.19)</a> is found that catches the thrown value. If no such <code>try</code> statement is found, then execution of the thread (<a href="memory.doc.html#26250">§17</a>) that executed the <code>throw</code> is terminated <a href="exceptions.doc.html#44153">(§11.3)</a> after invocation of the <code>uncaughtException</code> method for the thread group to which the thread belongs.<p>
<ul><pre>
<em>ThrowStatement:
</em>throw<em> Expression ;
</em></pre></ul><a name="236072"></a>
The <em>Expression</em> in a throw statement must denote a variable or value of a reference type which is assignable <a href="conversions.doc.html#184206">(§5.2)</a> to the type <code>Throwable</code>, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:<p>
<ul><a name="236073"></a>
<li>The exception is not a checked exception <a href="exceptions.doc.html#44121">(§11.2)</a>-specifically, one of the following situations is true:
<ul>
<a name="39922"></a>
<li>The type of the <em>Expression</em> is the class <code>RuntimeException</code> or a subclass of <code>RuntimeException</code>.
<a name="236074"></a>
<li>The type of the <em>Expression</em> is the class <code>Error</code> or a subclass of <code>Error</code>.
</ul>
<a name="236078"></a>
<li>The <code>throw</code> statement is contained in the <code>try</code> block of a <code>try</code> statement <a href="statements.doc.html#79311">(§14.19)</a> and the type of the <em>Expression</em> is assignable <a href="conversions.doc.html#184206">(§5.2)</a> to the type of the parameter of at least one <code>catch</code> clause of the <code>try</code> statement. (In this case we say the thrown value is <em>caught</em> by the <code>try</code> statement.)
<a name="236082"></a>
<li>The <code>throw</code> statement is contained in a method or constructor declaration and the type of the <em>Expression</em> is assignable <a href="conversions.doc.html#184206">(§5.2)</a> to at least one type listed in the <code>throws</code> clause (<a href="classes.doc.html#78323">§8.4.4</a>, <a href="classes.doc.html#244611">§8.8.4</a>) of the declaration.
</ul><a name="254469"></a>
A <code>throw</code> statement first evaluates the <em>Expression</em>. If the evaluation of the <em>Expression</em> completes abruptly for some reason, then the <code>throw</code> completes abruptly for that reason. If evaluation of the <em>Expression</em> completes normally, producing a non-<code>null</code> value <i>V</i>, then the <code>throw</code> statement completes abruptly, the reason being a <code>throw</code> with value <i>V</i>. If evaluation of the <em>Expression</em> completes normally, producing a <code>null</code> value, then an instance <i>V'</i> of class <code>NullPointerException</code> is created and thrown instead of <code>null</code>. The <code>throw</code> statement then completes abruptly, the reason being a <code>throw</code> with value<i> V'</i>.<p>
<a name="254470"></a>
It can be seen, then, that a <code>throw</code> statement always completes abruptly.<p>
<a name="254474"></a>
If there are any enclosing <code>try</code> statements <a href="statements.doc.html#79311">(§14.19)</a> whose <code>try</code> blocks contain the <code>throw</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>throw</code> statement.<p>
<a name="79283"></a>
If a <code>throw</code> statement is contained in a method declaration, but its value is not caught by some <code>try</code> statement that contains it, then the invocation of the method completes abruptly because of the <code>throw</code>.<p>
<a name="79284"></a>
If a <code>throw</code> statement is contained in a constructor declaration, but its value is not caught by some <code>try</code> statement that contains it, then the class instance creation expression that invoked the constructor will complete abruptly because of the <code>throw</code>.<p>
<a name="43567"></a>
If a <code>throw</code> statement is contained in a static initializer <a href="classes.doc.html#39245">(§8.7)</a>, then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some <code>try</code> statement that contains it. If at run-time, despite this check, the value is not caught by some <code>try</code> statement that contains the <code>throw</code> statement, then the value is rethrown if it is an instance of class <code>Error</code> or one of its subclasses; otherwise, it is wrapped in an <code>ExceptionInInitializerError</code> object, which is then thrown <a href="execution.doc.html#44630">(§12.4.2)</a>.<p>
<a name="248568"></a>
If a <code>throw</code> statement is contained in an instance initializer <a href="classes.doc.html#246032">(§8.6)</a>, then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it, or the type of the thrown exception (or one of its superclasses) occurs in the throws clause of every constructor of the class.<p>
<a name="255757"></a>
By convention, user-declared throwable types should usually be declared to be subclasses of class <code>Exception</code>, which is a subclass of class <code>Throwable</code> (<a href="exceptions.doc.html#44278">§11.5</a>).<p>
<a name="255769"></a>
<h2>14.18 The <code>synchronized</code> Statement</h2>
<a name="79291"></a>
A <code>synchronized</code> statement acquires a mutual-exclusion lock <a href="memory.doc.html#28460">(§17.13)</a> on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock.<p>
<ul><pre>
<em>SynchronizedStatement:
</em> synchronized<em> ( Expression ) Block
</em></pre></ul><a name="217233"></a>
The type of <em>Expression</em> must be a reference type, or a compile-time error occurs. <p>
<a name="217245"></a>
A <code>synchronized</code> statement is executed by first evaluating the <em>Expression</em>.<p>
<a name="236514"></a>
If evaluation of the <em>Expression</em> completes abruptly for some reason, then the <code>synchronized</code> statement completes abruptly for the same reason.<p>
<a name="236515"></a>
Otherwise, if the value of the <em>Expression</em> is <code>null</code>, a <code>NullPointerException</code> is thrown.<p>
<a name="247651"></a>
Otherwise, let the non-<code>null</code> value of the <em>Expression</em> be <i>V</i>. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the <em>Block</em> completes normally, then the lock is unlocked and the <code>synchronized</code> statement completes normally. If execution of the <em>Block</em> completes abruptly for any reason, then the lock is unlocked and the <code>synchronized</code> statement then completes abruptly for the same reason.<p>
<a name="79305"></a>
Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use <code>synchronized</code> methods or the <code>synchronized</code>  statement in a conventional manner to achieve mutual exclusion.<p>
<a name="79306"></a>
The locks acquired by <code>synchronized</code> statements are the same as the locks that are acquired implicitly by <code>synchronized</code> methods; see <a href="classes.doc.html#260369">§8.4.3.6</a>. A single thread may hold a lock more than once. <p>
<a name="252313"></a>
The example:<p>
<blockquote><pre>class Test {
public static void main(String[] args) {
Test t = new Test();
synchronized(t) {
synchronized(t) {
System.out.println("made it!");
}
}
}
}
</pre></blockquote><a name="22901"></a>
prints:<p>
<blockquote><pre>made it!
</pre></blockquote><a name="22903"></a>
This example would deadlock if a single thread were not permitted to lock a lock more than once.<p>
<a name="79311"></a>
<h2>14.19 The <code>try</code> statement</h2>
<a name="79312"></a>
A <code>try</code> statement executes a block. If a value is thrown and the <code>try</code> statement has one or more <code>catch</code> clauses that can catch it, then control will be transferred to the first such <code>catch</code> clause. If the <code>try</code> statement has a <code>finally</code> clause, then another block of code is executed, no matter whether the <code>try</code> block completes normally or abruptly, and no matter whether a <code>catch</code> clause is first given control. <p>
<ul><pre>
<em>TryStatement:
</em>try<em> Block Catches
</em>try<em> Block Catches<sub><i>opt</i></sub> Finally
Catches:
CatchClause
Catches CatchClause
CatchClause:
</em> catch<em> ( FormalParameter ) Block
Finally:
</em>finally<em> Block
</em></pre></ul><a name="250063"></a>
The following is repeated from <a href="classes.doc.html#38698">§8.4.1</a> to make the presentation here clearer:<p>
<ul><pre>
<em>FormalParameter:
</em>final<em><sub>opt</sub> Type VariableDeclaratorId
</em></pre></ul><a name="237406"></a>
The following is repeated from <a href="classes.doc.html#40898">§8.3</a> to make the presentation here clearer:<p>
<ul><pre>
<em>VariableDeclaratorId:
Identifier
VariableDeclaratorId</em> [ ]
</pre></ul><a name="79317"></a>
The <em>Block</em> immediately after the keyword <code>try</code> is called the <code>try</code> block of the <code>try</code> statement. The <em>Block</em> immediately after the keyword <code>finally</code> is called the <code>finally</code> block of the <code>try</code> statement.<p>
<a name="79318"></a>
A <code>try</code> statement may have <code>catch</code> clauses (also called <em>exception handlers</em>). A  <code>catch</code> clause must have exactly one parameter (which is called an <em>exception parameter</em>); the declared type of the exception parameter must be the class <code>Throwable</code> or a subclass of <code>Throwable</code>, or a compile-time error occurs. The scope of the parameter variable is the <em>Block</em> of the <code>catch</code> clause. <p>
<a name="247654"></a>
An exception parameter of a catch clause must not have the same name as a local variable or parameter of the method or initializer block immediately enclosing the catch clause, or a compile-time error occurs.<p>
<a name="257131"></a>
The scope of a parameter of an exception handler that is declared in a <code>catch</code> clause of a <code>try</code> statement <a href="statements.doc.html#79311">(§14.19)</a> is the entire block associated with the <code>catch</code>.<p>
<a name="247671"></a>
Within the <em>Block</em> of the <code>catch</code> clause, the name of the parameter may not be redeclared as a local variable of the directly enclosing method or initializer block, nor may it be redeclared as an exception parameter of a catch clause in a try statement of the directly enclosing method or initializer block, or a compile-time error occurs. However, an exception parameter may be shadowed <a href="names.doc.html#34133">(§6.3.1)</a> anywhere inside a class declaration nested within the Block of the catch clause. <p>
<a name="247536"></a>
It is a compile-time error if an exception parameter that is declared final is assigned to within the body of the catch clause. <p>
<a name="45880"></a>
Exception parameters cannot be referred to using qualified names <a href="names.doc.html#104285">(§6.6)</a>, only by simple names.<p>
<a name="24142"></a>
Exception handlers are considered in left-to-right order: the earliest possible <code>catch</code> clause accepts the exception, receiving as its actual argument the thrown exception object.<p>
<a name="24143"></a>
A <code>finally</code> clause ensures that the <code>finally</code> block is executed after the <code>try</code> block and any <code>catch</code> block that might be executed, no matter how control leaves the <code>try</code> block or <code>catch</code> block.<p>
<a name="79319"></a>
Handling of the <code>finally</code> block is rather complex, so the two cases of a <code>try</code> statement with and without a <code>finally</code> block are described separately.<p>
<a name="24134"></a>
<h3>14.19.1 Execution of try-catch<code><b></b></code></h3>
<a name="79320"></a>
A <code>try</code> statement without a <code>finally</code> block is executed by first executing the <code>try</code> block. Then there is a choice:<p>
<ul><a name="79321"></a>
<li>If execution of the <code>try</code> block completes normally, then no further action is taken and the <code>try</code> statement completes normally.
<a name="79322"></a>
<li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <i>V</i>, then there is a choice:
<ul>
<a name="79323"></a>
<li>If the run-time type of <i>V</i><i></i> is assignable <a href="conversions.doc.html#184206">(§5.2)</a> to the <em>Parameter</em> of any <code>catch</code> clause of the <code>try</code> statement, then the first (leftmost) such <code>catch</code> clause is selected. The value <i>V</i> is assigned to the parameter of the selected <code>catch</code> clause, and the <em>Block</em> of that <code>catch</code> clause is executed. If that block completes normally, then the <code>try</code> statement completes normally; if that block completes abruptly for any reason, then the <code>try</code> statement completes abruptly for the same reason.
<a name="79324"></a>
<li>If the run-time type of <i>V</i> is not assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the <code>try</code> statement completes abruptly because of a <code>throw</code> of the value <i>V</i>.
</ul>
<a name="79325"></a>
<li>If execution of the <code>try</code> block completes abruptly for any other reason, then the <code>try</code> statement completes abruptly for the same reason.
<a name="256055"></a>
In the example:<p>
</ul><blockquote><pre>class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt { throw new BlewIt(); }
public static void main(String[] args) {
try {
blowUp();
} catch (RuntimeException r) {
System.out.println("RuntimeException:" + r);
} catch (BlewIt b) {
System.out.println("BlewIt");
}
}
}
</pre></blockquote><a name="236651"></a>
the exception <code>BlewIt</code> is thrown by the method <code>blowUp</code>. The <code>try</code><strong>-</strong><code>catch</code> statement in the body of <code>main</code> has two <code>catch</code> clauses. The run-time type of the exception is <code>BlewIt</code> which is not assignable to a variable of type <code>RuntimeException</code>, but is assignable to a variable of type <code>BlewIt</code>, so the output of the example is:<p>
<blockquote><pre>BlewIt
</pre></blockquote><a name="236653"></a>
<h3>14.19.2 Execution of try-catch-finally<code><b></b></code></h3>
<a name="79326"></a>
A <code>try</code> statement with a <code>finally</code> block is executed by first executing the <code>try</code> block. Then there is a choice:<p>
<ul><a name="79327"></a>
<li>If execution of the <code>try</code> block completes normally, then the <code>finally</code> block is executed, and then there is a choice:
<ul>
<a name="160341"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes normally.
<a name="160342"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i>.
</ul>
<a name="79328"></a>
<li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <i>V</i>, then there is a choice:
<ul>
<a name="79329"></a>
<li>If the run-time type of <i>V</i> is assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the first (leftmost) such <code>catch</code> clause is selected. The value <i>V</i> is assigned to the parameter of the selected <code>catch</code> clause, and the <em>Block</em> of that <code>catch</code> clause is executed. Then there is a choice:
<ul>
<a name="79330"></a>
<li>If the <code>catch</code> block completes normally, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="160348"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes normally.
<a name="160349"></a>
<li>If the <code>finally</code> block completes abruptly for any reason, then the <code>try</code> statement completes abruptly for the same reason.
</ul>
<a name="79331"></a>
<li>If the <code>catch</code> block completes abruptly for reason <i>R</i>, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79332"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly for reason <i>R</i>.
<a name="79333"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i> (and reason <i>R</i> is discarded).
</ul>
</ul>
<a name="79334"></a>
<li>If the run-time type of <i>V</i> is not assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79335"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly because of a <code>throw</code> of the value <i>V</i>.
<a name="79336"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i> (and the <code>throw</code> of value <i>V</i> is discarded and forgotten).
</ul>
</ul>
<a name="79337"></a>
<li>If execution of the <code>try</code> block completes abruptly for any other reason <i>R</i>, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79338"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly for reason <i>R</i>.
<a name="79339"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i> (and reason <i>R</i> is discarded).
<a name="252337"></a>
The example:<p>
</ul>
</ul><blockquote><pre>class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt {
throw new NullPointerException();
}
public static void main(String[] args) {
try {
blowUp();
} catch (BlewIt b) {
System.out.println("BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
}
}
</pre></blockquote><a name="18070"></a>
produces the output:<p>
<blockquote><pre>Uncaught Exception
java.lang.NullPointerException
at Test.blowUp(Test.java:7)
at Test.main(Test.java:11)
</pre></blockquote><a name="236703"></a>
The <code>NullPointerException</code> (which is a kind of <code>RuntimeException</code>) that is thrown by method <code>blowUp</code> is not caught by the <code>try</code> statement in <code>main</code>, because a <code>NullPointerException</code> is not assignable to a variable of type <code>BlewIt</code>. This causes the <code>finally</code> clause to execute, after which the thread executing <code>main</code>, which is the only thread of the test program, terminates because of an uncaught exception, which typically results in printing the exception name and a simple backtrace.<p>
<a name="236365"></a>
<h2>14.20 Unreachable Statements</h2>
<a name="237365"></a>
It is a compile-time error if a statement cannot be executed because it is <em>unreachable</em>. Every Java compiler must carry out the conservative flow analysis specified here to make sure all statements are reachable.<p>
<a name="237366"></a>
This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, instance initializer or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of <code>while</code>, <code>do</code>, and <code>for</code> statements whose condition expression has the constant value <code>true</code>, the values of expressions are not taken into account in the flow analysis. <p>
<a name="252350"></a>
For example, a Java compiler will accept the code:<p>
<blockquote><pre>{
int n = 5;
while (n > 7) k = 2;
}
</pre></blockquote><a name="79350"></a>
even though the value of <code>n</code> is known at compile time and in principle it can be known at compile time that the assignment to <code>k</code> can never be executed.<p>
<a name="252357"></a>
A Java compiler must operate according to the rules laid out in this section.<p>
<a name="79351"></a>
The rules in this section define two technical terms:<p>
<ul><a name="79352"></a>
<li>whether a statement is <em>reachable</em>
<a name="79353"></a>
<li>whether a statement <em>can complete normally</em>
</ul><a name="79354"></a>
The definitions here allow a statement to complete normally only if it is reachable.<p>
<a name="236611"></a>
To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."<p>
<a name="236612"></a>
The rules are as follows:<p>
<ul><a name="236613"></a>
<li>The block that is the body of a constructor, method, instance initializer or static initializer is reachable.
<a name="160362"></a>
<li>An empty block that is not a switch block can complete normally iff it is reachable. A nonempty block that is not a switch block can complete normally iff the last statement in it can complete normally. The first statement in a nonempty block that is not a switch block is reachable iff the block is reachable. Every other statement <i>S</i> in a nonempty block that is not a switch block is reachable iff the statement preceding <i>S</i> can complete normally.
<a name="247970"></a>
<li>A local class declaration statement can complete normally iff it is reachable.
<a name="160365"></a>
<li>A local variable declaration statement can complete normally iff it is reachable.
<a name="79357"></a>
<li>An empty statement can complete normally iff it is reachable.
<a name="79359"></a>
<li>A labeled statement can complete normally if at least one of the following is true:
<ul>
<a name="21184"></a>
<li>The contained statement can complete normally.
<a name="21188"></a>
<li>There is a reachable <code>break</code> statement that exits the labeled statement.
</ul>
</ul><ul><a name="21187"></a>
The contained statement is reachable iff the labeled statement is reachable.
</ul><ul><a name="79360"></a>
<li>An expression statement can complete normally iff it is reachable.
<a name="236410"></a>
<li>The <code>if</code> statement, whether or not it has an <code>else</code> part, is handled in an unusual manner. For this reason, it is discussed separately at the end of this section.
<a name="79366"></a>
<li>A <code>switch</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79367"></a>
<li>The last statement in the switch block can complete normally.
<a name="237563"></a>
<li>The switch block is empty or contains only switch labels.
<a name="248980"></a>
<li>There is at least one switch label after the last switch block statement group.
<a name="248989"></a>
<li>The switch block does not contain a <code>default</code> label.
<a name="248981"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>switch</code> statement.
</ul>
<a name="237548"></a>
<li>A switch block is reachable iff its <code>switch</code> statement is reachable.
<a name="237550"></a>
<li>A statement in a switch block is reachable iff its <code>switch</code> statement is reachable and at least one of the following is true:
<ul>
<a name="79370"></a>
<li>It bears a <code>case</code> or <code>default</code> label.
<a name="79371"></a>
<li>There is a statement preceding it in the <code>switch</code> block and that preceding statement can complete normally.
</ul>
<a name="79372"></a>
<li>A <code>while</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79373"></a>
<li>The <code>while</code> statement is reachable and the condition expression is not a constant expression with value <code>true</code>.
<a name="79374"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>while</code> statement.
</ul>
</ul><ul><a name="79375"></a>
The contained statement is reachable iff the <code>while</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.
</ul><ul><a name="79376"></a>
<li>A <code>do</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79377"></a>
<li>The contained statement can complete normally and the condition expression is not a constant expression with value <code>true</code>.
<a name="248990"></a>
<li>The <code>do</code> statement contains a reachable <code>continue</code> statement with no label, and the <code>do</code> statement is the innermost <code>while</code>, <code>do</code>, or <code>for</code> statement that contains that <code>continue</code> statement, and the condition expression is not a constant expression with value <code>true</code>.
<a name="248991"></a>
<li>The <code>do</code> statement contains a reachable <code>continue</code> statement with a label <i>L</i>, and the <code>do</code> statement has label <i>L, </i>and the condition expression is not a constant expression with value <code>true</code>.
<a name="79378"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>do</code> statement.
</ul>
</ul><ul><a name="79379"></a>
The contained statement is reachable iff the <code>do</code> statement is reachable.
</ul><ul><a name="79380"></a>
<li>A <code>for</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79381"></a>
<li>The <code>for</code> statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value <code>true</code>.
<a name="79382"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>for</code> statement.
</ul>
</ul><ul><a name="79383"></a>
The contained statement is reachable iff the <code>for</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.
</ul><ul><a name="79384"></a>
<li>A <code>break</code>, <code>continue</code>, <code>return</code>, or <code>throw</code> statement cannot complete normally.
<a name="79385"></a>
<li>A <code>synchronized</code> statement can complete normally iff the contained statement can complete normally. The contained statement is reachable iff the <code>synchronized</code> statement is reachable.
<a name="79386"></a>
<li>A <code>try</code> statement can complete normally iff both of the following are true:
<ul>
<a name="79387"></a>
<li>The <code>try</code> block can complete normally or any <code>catch</code> block can complete <code>normally</code>.
<a name="79388"></a>
<li>If the <code>try</code> statement has a <code>finally</code> block, then the <code>finally</code> block can complete normally.
</ul>
<a name="79389"></a>
<li>The <code>try</code> block is reachable iff the <code>try</code> statement is reachable.
<a name="79390"></a>
<li>A <code>catch</code> block <i>C</i> is reachable iff both of the following are true:
<ul>
<a name="79391"></a>
<li>Some expression or <code>throw</code> statement in the <code>try</code> block is reachable and can throw an exception whose type is assignable to the parameter of the <code>catch</code> clause <i>C</i>. (An expression is considered reachable iff the innermost statement containing it is reachable.)
<a name="79392"></a>
<li>There is no earlier <code>catch</code> block <i>A</i> in the <code>try</code> statement such that the type of <i>C</i>'s parameter is the same as or a subclass of the type of <i>A</i>'s parameter.
</ul>
<a name="236212"></a>
<li>If a <code>finally</code> block is present, it is reachable iff the <code>try</code> statement is reachable.
<a name="236419"></a>
One might expect the <code>if</code> statement to be handled in the following manner, but these are not the rules that the Java programming language actually uses:<p>
<a name="236554"></a>
<li>HYPOTHETICAL: An <code>if-then</code> statement can complete normally iff at least one of the following is <code>true</code>:
<ul>
<a name="236555"></a>
<li>The <code>if</code>-<code>then</code> statement is reachable and the condition expression is not a constant expression whose value is <code>true</code>.
<a name="236407"></a>
<li>The <code>then</code>-statement can complete normally.
</ul>
</ul><a name="236408"></a>
The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.<p>
<ul><a name="236409"></a>
<li>HYPOTHETICAL: An <code>if</code>-<code>then</code>-<code>else</code> statement can complete normally iff the <code>then</code>-statement can complete normally or the <code>else</code>-statement can complete normally. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>. The <code>else</code> statement is reachable iff the <code>if</code>-<code>then</code>-<code>else </code>statement is reachable and the condition expression is not a constant expression whose value is <code>true</code>.
<a name="236422"></a>
This approach would be consistent with the treatment of other control structures. However, in order to allow the if statement to be used conveniently for "conditional compilation" purposes, the actual rules differ.<p>
</ul><a name="252364"></a>
The actual rules for the if statement are as follows:<p>
<ul><a name="236424"></a>
<li>ACTUAL: An <code>if</code>-<code>then</code> statement can complete normally iff it is reachable. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code> statement is reachable.
<a name="236428"></a>
<li>ACTUAL: An <code>if</code>-<code>then</code>-<code>else</code> statement can complete normally iff the <code>then</code>-statement can complete normally or the <code>else</code>-statement can complete normally. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable. The <code>else</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable.
<a name="252376"></a>
As an example, the following statement results in a compile-time error:<p>
</ul><blockquote><pre>while (false) { x=3; }
</pre></blockquote><a name="236453"></a>
because the statement <code>x=3;</code> is not reachable; but the superficially similar case:<p>
<blockquote><pre>if (false) { x=3; }
</pre></blockquote><a name="236454"></a>
does not result in a compile-time error. An optimizing compiler may realize that the statement <code>x=3;</code> will never be executed and may choose to omit the code for that statement from the generated <code>class</code> file, but the statement <code>x=3;</code> is not regarded as "unreachable" in the technical sense specified here.<p>
<a name="238244"></a>
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:<p>
<blockquote><pre>static final boolean DEBUG = false;
</pre></blockquote><a name="236471"></a>
and then write code such as:<p>
<blockquote><pre>if (DEBUG) { x=3; }
</pre></blockquote><a name="236477"></a>
The idea is that it should be possible to change the value of <code>DEBUG</code> from <code>false</code> to <code>true</code> or from <code>true</code> to <code>false</code> and then compile the code correctly with no other changes to the program text.<p>
<a name="238425"></a>
This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility <a href="binaryComp.doc.html#44871">(§13)</a>. If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries <a href="binaryComp.doc.html#45139">(§13.4.8)</a>. (There are other reasons for such incompatibility as well, such as the use of constants in <code>case</code> labels in <code>switch</code> statements; see <a href="binaryComp.doc.html#45139">§13.4.8</a>.)<p>
<hr>
<table border="0" width="100%">
<tr>
<td><a href="jTOC.doc.html">Contents</a> | <a href="binaryComp.doc.html">Prev</a> | <a href="expressions.doc.html">Next</a> | <a href="jIX.fm.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">Second Edition</font></td></tr></table>
<i><a href="jcopyright.doc.html">Copyright</a> © 2000 Sun Microsystems, Inc.
All rights reserved</i>
<br>
Please send any comments or corrections to <a href="mailto:
[email protected]">
[email protected]</a>
</font>
</body></html>