Variable Scopes in Java

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

  1. Class Scope
  2. Method Scope
  3. Loop Scope
  4. 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.

public class ScopeExample {
 
private String classScopedVariable=”xyz”;
 
}
 

Method Scope

 
The variables defined inside the method and the method arguments are under method scope. These are only accessible inside the method only where it is defined.
 
public void method(String methodScopedParameter) {
String methodScopedVariable=”abc”;
}
 

Loop Scope

The variables defined inside while or for loop are accessible inside the loop only and hence are called loop scoped variables.

for(int loopScopedVariable=0;  loopScopedVariable < 10; loopScopedVariable++) {
 
System.out.println(“loopScopedVariable:”+loopScopedVariable);
 
}
 

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.

{
 
String blockScopedVariable=”123″;
System.out.println(“blockScopedVariable:”+blockScopedVariable);
 
}
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

Leave a Reply

Your email address will not be published. Required fields are marked *