Friday, 25 April 2008

Definitive Assignment Chapter in JLS 3rd Edition

Today i started reading Chapter 16 Definitive Assignment in JLS 3rd Edition.

There are Few Key Points i wanted to share in this chapter.

A related example illustrates rules of definite unassignment. A Java compiler will accept the code:


void unflow(boolean flag) {
final int k;
if (flag) {
k = 3;
System.out.println(k);
}
else {
k = 4;
System.out.println(k);
}
}


as far as definite unassignment of k is concerned, because the rules outlined in this section allow it to tell that k is assigned at most once (indeed, exactly once) no matter whether the flag is true or false. But the rules do not accept the variation:


void unflow(boolean flag) {
final int k;
if (flag) {
k = 3;
System.out.println(k);
}
if (!flag) {
k = 4; // k is not "definitely unassigned" before here
System.out.println(k);
}
}


In order to precisely specify all the cases of definite assignment, the rules in this section define several technical terms:


whether a variable is definitely assigned before a statement or expression;
whether a variable is definitely unassigned before a statement or expression;
whether a variable is definitely assigned after a statement or expression; and
whether a variable is definitely unassigned after a statement or expression.
For boolean-valued expressions, the last two are refined into four cases:

whether a variable is definitely assigned after the expression when true;
whether a variable is definitely unassigned after the expression when true;
whether a variable is definitely assigned after the expression when false; and
whether a variable is definitely unassigned after the expression when false.
Here when true and when false refer to the value of the expression.

For example, the local variable k is definitely assigned a value after evaluation of the expression


a && ((k=m) > 5)


when the expression is true but not when the expression is false (because if a is false, then the assignment to k is not necessarily executed (more properly, evaluated)).

Hope this explanation helps if any.

No comments: