Вопрос

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];
 }
Это было полезно?

Решение 2

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.

Другие советы

See the comments

public static void main(String[] args) {
    System.out.println(toHelp); // using the already initialize static variable
    String toHelp = args[0]; // shadowing the static variable with a local variable
} 

Shadowing is explained in the Java Language Specification here.

After the execution of

String toHelp = args[0];

you have two variables with the name toHelp in scope. The local one can be accessed with its name toHelp. The class static variable needs to now be accessed with ClassName.toHelp because it is shadowed.

public static String toHelp = "--help";

You already declared it and defined it equal to "--help".

The scanner input would just set it again.

toHelp is a static variable. Its visible to your main() as its already declared and initialized.

And if you're asking about the args, then its a method parameter and therefore, its already declared as a part of the method declaration itself.

If its a instance variable, then you can use this.toHelp to access that in the method. And (as in this case) its a static variable and you can use the ClassName.toHelp to differentiate the 2 variables.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top