A variable can be accessed and used inside it’s designated scope.
The scope of the variable is defined by the block within which it is defined.
We have the following scopes
- Class Scope
- Method Scope
- Loop Scope
- Block Scope
Class Scope
The instance variables defined at the class level come under class scope category. In the below example classScopedVariable is in Class Scope. Please note that class scoped variables are accessible throughout the class.
Method Scope
Loop Scope
The variables defined inside while or for loop are accessible inside the loop only and hence are called loop scoped variables.
Block Scope
The variables defined inside a block be it a try or catch block or instance block or normal block is only accessible inside that block only.
package com.java.core;
public class ScopeExample {
private String classScopedVariable = "xyz";
public void method(String methodScopedParameter) {
String methodScopedVariable = "abc";
System.out.println("methodScopedVariable:" + methodScopedVariable);
System.out.println("methodScopedParameter:" + methodScopedParameter);
for (int loopScopedVariable = 0; loopScopedVariable < 10; loopScopedVariable++) {
System.out.println("loopScopedVariable:" + loopScopedVariable);
}
{
String blockScopedVariable = "123";
System.out.println("blockScopedVariable:" + blockScopedVariable);
System.out.println("classScopedVariable:" + classScopedVariable);
}
}
public static void main(String[] args) {
ScopeExample scopeExample = new ScopeExample();
scopeExample.method("gyan");
}
}
methodScopedVariable:abc
methodScopedParameter:gyan
loopScopedVariable:0
loopScopedVariable:1
loopScopedVariable:2
loopScopedVariable:3
loopScopedVariable:4
loopScopedVariable:5
loopScopedVariable:6
loopScopedVariable:7
loopScopedVariable:8
loopScopedVariable:9
blockScopedVariable:123
classScopedVariable:xyz