Reputation: 3
I declared a private static double fd
and then I declared double fd
again inside the main(). Why can I compile and run it successfully?
public class HelloWorld {
private static double fd = 1.0;
public static void main(String[] args){
System.out.println(fd); //1.0
double fd = 2.0;
System.out.println(fd); //2.0
}
}
Upvotes: 0
Views: 98
Reputation: 990
From JLS Scope of a Declaration section:
The scope of a declaration is the region of the program within which the entity declared by the declaration can be referred to using a simple name, provided it is not shadowed.
From JLS Shadowing section:
Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
This means that you cannot use simple name (df
) to refer class level df
variable, because of it's shadowed by local df
variable. But there are still two variables and you can use static variable with class name:
public static void main(String[] args){
System.out.println(fd); //1.0
double fd = 2.0;
System.out.println(fd); //2.0
System.out.println(HelloWorld.fd);
}
Upvotes: 1
Reputation: 190
This is not a syntax error (although it will probably result in a logic error, a bug). The compiler will compile this code without complaint. The second declaration of double fd creates a local variable for the main method. The scope of this variable starts with its declaration and ends at the end of the block (as with all local variables). So the next statement uses the local variable, not the instance variable.
The local variable will no longer hold a value after the method has returned. The instance variable will not have been changed.
Hint: Think of statements as looking "upward" from their own location to find each of their variables. They can look outside of their "glass box" in any direction if they fail to find a variable inside their own method.
It is almost always a mistake to use the same name for an instance variable and for a local variable. But it is not a syntax error, so the compiler will not warn you.
Upvotes: 0
Reputation: 1248
The variable fd is function scoped, think it like, the compiler first check the scope nearest to it, and then if it dosent find there it tries to check the global scope, if it found something in local scope, it will print that, or else moves on to check other scope.
Upvotes: 0