Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Scope


Scope can be defined as the accessibility of a variable.


Say for example, in every office, there is a restricted area where only a few people have access.


Similarly, in Java, the variables also have some access restrictions. The variables that are defined inside a Method, cannot be accessed outside of it.


Example :



public class MyApplication {
    public static void main(String[] args) {

        myMethod();
        System.out.println(x);
    }

    static void myMethod() {
        int x = 5;
    }
}


Output :



  java: cannot find symbol
  symbol: variable x
  location: class com.tgt.MyApplication

So, in the first line itself, the Method myMethod() is called.


myMethod();

And the function execution begins.


static void myMethod()
{
	int x = 5;
}

And initialised the variable x with 5 inside the function myMethod().


int x = 5;
Spring_Boot


Then we come to the print statement,


System.out.println(x);

And end up with an error as output,

Output :



  java: cannot find symbol
  symbol: variable x
  location: class com.tgt.MyApplication

This is because the variable x is not accessable outside the Method. And that is called as Local Scope.


Local Scope


The variables that are declared inside a Method, can only be accessed inside the Method and is local to that Method. That is called the Local Scope of a variable.


Say for example, if there are two functions, firstMethod() and secondMethod().


Example :



public class MyApplication {
    public static void main(String[] args) {

        firstMethod();
        secondMethod();
    }

    static void firstMethod() {
        int x = 5;
        System.out.println("The variable x : "+x+" is not accesible outside the firstMethod()");
    }

    static void secondMethod() {
        int y = 7;
        System.out.println("The variable y : "+y+" is not accesible outside the secondMethod()");
    }
}


Output :



  The variable x : 5 is not accesible outside the firstMethod()
  The variable y : 7 is not accesible outside the secondMethod()

So, we have declared two functions, firstMethod(),


static void firstMethod()
{
	int x = 5;
	System.out.println("The variable x : "+x+" is not accesible outside the firstMethod()");
}

And secondMethod().


static void secondMethod()
{
	int y = 7;
	System.out.println("The variable y : "+y+" is not accesible outside the secondMethod()");
}

And we have two variables, x and y.


While x is declared inside the Method firstMethod() and is local to the firstMethod() and cannot be accessed outside it.


Similarly, y is declared inside the Method secondMethod() and is local to the secondMethod() and cannot be accessed outside it.