Feedback and comments on ARM proposal - resend
Neal Gafter
neal at gafter.com
Wed Mar 18 08:18:24 PDT 2009
On Wed, Mar 18, 2009 at 1:15 AM, Jeremy Manson <jeremy.manson at gmail.com> wrote:
> I'm pretty sure that it is only definitely unassigned there if it is
> definitely unassigned after the switch expression. If you want it to
> compile, you have to place the declaration before the switch
> statement. I could be wrong about that.
JLS 16.2.2 says
# A local variable V is definitely unassigned (and moreover is not
definitely assigned) before the block that is the body of the
constructor, method, instance initializer or static initializer that
declares V .
So moving the declaration up should have no impact. And yet the
following program compiles. Why should this compile and the previous
one fail to compile?
import java.io.*;
class T {
public static void main(String[] args) {
switch (args.length) {
case 0:
final int i;
i = 0;
break;
case 1:
i = 1; // i is definitely unassigned here, so we assign to it
System.out.println(i);
break;
}
}
}
spoiler below.
The answer can be found in JLS 15.26: "A variable that is declared
final cannot be assigned to (unless it is a definitely unassigned
(§16) blank final variable (§4.12.4)), ..."
Note particularly the word "blank". You're not allowed to assign to a
final variable that is definitely unassigned unless it is a blank
final. The original version of this puzzler is the only way to create
a variable that is final and definitely unassigned, but not a blank
final. It also shows a way to create a constant variable that is not
definitely assigned. Should the following snippet compile?
switch (args.length) {
case 0:
final int i = 0; // declare a constant
break;
case 1:
System.out.println(i); // print the value of the constant variable
break;
}
The point of this series of puzzles is that, due to the strangeness of
the switch statement, building a resource language construct based on
variable scope can be subtle. The simplest way to avoid problems is
to say that you can't use a resource-variable-declaration-statement at
the top level within a switch statement.
More information about the coin-dev
mailing list