Java Reference
In-Depth Information
System.out.println(k); /* k is not "definitely assigned"
before this statement */
}
must be rejected by a Java compiler, because in this case the while statement is not
guaranteed to execute its body as far as the rules of definite assignment are concerned.
Example 16-2. Definite Assignment Does Not Consider Values of Expressions
A Java compiler must produce a compile-time error for the code:
Click here to view code image
{
int k;
int n = 5;
if (n > 2)
k = 3;
System.out.println(k); /* k is not "definitely assigned"
before this statement */
}
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, eval-
uated). 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.28 .
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 sec-
tion 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:
Click here to view code image
void flow(boolean flag) {
int k;
Search WWH ::




Custom Search