I am learning Java and I understand that you cannot name a variable declared within an inner scope the same name as a variable declared in an outer scope as shown below
public class Practice { public static void main(String[] args){ int x = 10; if (x == 10){ int x = 10; } } }
However, I noticed that the following is not illegal
public class Practice { int x = 10; public static void main(String[] args){ int x = 10; if (x == 10) { } } }
Is this not a variable that is declared twice??
Advertisement
Answer
Is this not a variable that is declared twice??
No, it is not. Because they both are in different scope. x
outside of main
function has class level scope while x
inside of main
has method/function level scope.
It is legal for 2 variables in different scope to have same name.
Please DO read §6.3. Scope of a Declaration from JLS. Below are few of the statement from that 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 visible (§6.4.1).
A declaration is said to be in scope at a particular point in a program if and only if the declaration’s scope includes that point.
The scope of a local variable declaration in a block (§14.4) is the rest of the block in which the declaration appears, starting with its own initializer and including any further declarators to the right in the local variable declaration statement.
There are lot of concepts related to scope like shadowing, so do read §6.4. Shadowing and Obscuring.
JLS is the best place to learn what is allowed and what is not allowed in Java. Feel free to read sections there.