Scope in Java
- Eclipse: Oxygen
- Java: 1.8
The scope of the variable is defined by the passage of the variable in which it can be used and accessed. The scope is an important concept in the OOPS. We have learned that public, private, protected, and default which is the package. These are the scope operators which operate on a variable to decide their existence in various parts of the code.
The following code demonstrates the variables declared within a method have a method level scope and cannot be accessed outside the method.
The Scope of variables method has a variable defined with the name i. This variable (local variable) is defined within the main method, which is initialized in for loop.
A variable i is accessed within the method, it will check the declaration of the variable in the current scope (that is, between braces). How the statement is in its current scope. in the main method, the local variable i is accessed in its current scope. Then, this variable takes the value and the println() method will print the output.
1 2 3 4 5 6 7 8 9 10 11 12 |
public class App { public static void main(String[] args) { int i; for (i = 1; i < 6; i++) { System.out.println(i); } System.out.println("**********"); System.out.println(i); } } |
Output
1
2
3
4
5
**********
6
Another example, consider the following program with a for loop. A variable declared within the pair of brackets “{” and “}” in a for loop has scope in square brackets.
1 2 3 4 5 6 7 8 9 |
public class App { public static void main(String[] args) { for (int i = 0; i < 6; i++) { System.out.println(i); } } } |
Output
0
1
2
3
4
5
In the following code demonstrate the public class App has two variables defined with the same name (i). A variable (local variable) is defined within the main method, which is initialized to 5, and another variable (instance variable) is declared inside the class, which is initialized to 100. When an instance of the Scope of Variables class is created, its constructor is invoked. As the variable i is accessed within the constructor, it will verify the declaration of the variable in the current scope (that is, between braces). Since the statement is not in its current scope, it goes to the upper level and verifies the declaration of the variable. As defined in the class (outside the method), now, the variable takes the value 100 and the program shows the first line of the output. On the other hand, in the main method, the local variable i is accessed in its current scope. Here, the local variable hides the instance variable. Then, this variable takes the value 5 and the println() method will print the second line of the output.
1 2 3 4 5 6 7 8 9 10 11 |
public class App { static int i = 100; public static void main(String[] args) { { int i = 5; System.out.println(i); } System.out.println(i); } } |
Output
5
100
Contributed by: Poonam Tomar