16
Definite Assignment
DEFINITE ASSIGNMENT
{
int k;
while (true) {
k = n;
if (k >= 5) break;
n = 6;
}
System.out.println(k);
}
the variable
k
is definitely assigned by the
while
statement because the condition
expression
true
never has the value
false
, so only the
break
statement can
cause the
while
statement to complete normally, and
k
is definitely assigned
before the
break
statement.
Except for the special treatment of certain boolean operators and of boolean
valued constant expressions, the values of expressions are not taken into account
in the flow analysis. For example, a Java compiler must produce a compile time
error for the code:
{
int k;
int n = 5;
if (n > 2)
k = 3;
System.out.println(k);// k
is not definitely assigned before this
}
even though the value of
n
is known at compile time, and in principle it can be
known at compile time that the assignment to
k
will always be executed (more
properly, evaluated). A Java compiler must operate according to the rules laid out
in this section. The rules recognize only constant expressions; in this example, the
expression
n > 2
is not a constant expression as defined in 15.27.
As another example, a Java compiler will accept the code:
void flow(boolean flag) {
int k;
if (flag)
k = 3;
else
k = 4;
System.out.println(k);
}
as far as definite assignment of
k
is concerned, because the rules outlined in this
section allow it to tell that
k
is assigned no matter whether the flag is
true
or
false
. But the rules do not accept the variation:
384
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved