Java Reference
In-Depth Information
Example 16-1. Definite Assignment Considers Structure of Statements and Ex-
pressions
A Java compiler recognizes that k is definitely assigned before its access (as an argu-
ment of a method invocation) in the code:
Click here to view code image
{
int k;
if (v > 0 && (k = System.in.read()) >= 0)
System.out.println(k);
}
because the access occurs only if the value of the expression:
v > 0 && (k = System.in.read()) >= 0
is true , and the value can be true only if the assignment to k is executed (more properly,
evaluated).
Similarly, a Java compiler will recognize that in the code:
{
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 ex-
pression 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.
On the other hand, the code:
Click here to view code image
{
int k;
while (n < 4) {
k = n;
if (k >= 5) break;
n = 6;
}
Search WWH ::




Custom Search