Gurpeet, thanks for posing a very interesting question. As you probably already know, since
y is an uninitialized local final variable, you are allowed to perform at most one assignment to it. Performing more than one assignment to a final local variable is a compile-time error.
Contrary to what you may expect, however, the
Java compiler does not attempt to exhaustively analyze your program's control flow to determine with 100% accuracy which parts of your program are unreachable. Instead, to enforce the "at most one assignment" rule, the compiler uses a simpler rule: a final local variable must be "
definitely unassigned" when it encounters an assignment to it, where "definitely unassigned" has a very precise meaning as defined in the Java Language Specification.
In CASE1, the compiler knows that the second assignment will never be reached, so there is no error. But in CASE2, the second assignment is reachable--but because there was an assignment statement before it,
y is
not definitely unassigned according to the precise rules defining the term. To you and me, we all know that both code fragments will only result in one assignment... but because the compiler depends on a simplified set of rules to make its judgment, it chooses to flag this as an error.
If you're interested in all the sordid details of what makes a variable "definitely unassigned" (and, conversely, "definitely assigned"), refer to this JLS page: (warning: long and confusing algorithm details inside!)
http://java.sun.com/docs/books/jls/second_edition/html/defAssign.doc.html#25979 Here's another example from the JLS page that illustrates the known limitations of the "definitely unassigned" rules:
The above code will
not compile. But this code will compile:
The above pair of programs are very similar to the programs in your original post.
[ November 07, 2007: Message edited by: Kelvin Lim ]