What are the rules for initialization of local variables before the point they are declared? Is it possible to use a variable before it is declared? I see on this page (Local Variable Declaration Issue) that it is illegal, yet when I try it works:
public static String toHelp = "--help";
public static void main(String[] args) {
System.out.println(toHelp);
String toHelp = args[0];
}
The reason you're confused is that the rules of local variable scoping are different in C# and Java - For Java (you posted the question with a Java tag) the scope begins at the point where the variable declaration occurs and extends downward to the end of the enclosing block. So in your example the println
actually doesn't take the local variable into account but the static field because the local variable was technically not in scope at that point.
If you did the same thing in C# (the link you included is for C# and not Java) you would indeed get an error. There the rules of scoping are different - in C# the the scope of a variable is the entire enclosing block, so it also includes the statements that precede the declaration but appear in the block. If your sample was C#, the first statement in main
would be accessing a non-initialized variable and that is a compiler error.