Scope of Variables

In programming, scope of variable defines how a specific variable is accessible within the program or across classes.

In programming, a variable can be declared and defined inside a class, method, or block. It defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable declared inside a block or method are not visible to outside. If we try to do so, we will get a compilation error. Note that the scope of a variable can be nested.

  • We can declare variables anywhere in the program but it has limited scope.
  • A variable can be a parameter of a method or constructor.
  • A variable can be defined and declared inside the body of a method and constructor.
  • It can also be defined inside blocks and loops.
  • Variable declared inside main() function cannot be accessed outside the main() function

 

 In Java, there are three types of variables based on their scope:

  1. Member Variables (Class Level Scope)
  2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)

These are the variables that are declared inside the class but outside any function have class-level scope. We can access these variables anywhere inside the class. Note that the access specifier of a member variable does not affect the scope within the class. Java allows us to access member variables outside the class with the following rules:


 


 

We see that y=100 is unknown. If you want to compile and run the above program remove or comment the statement y=100. After removing the statement, the above program runs successfully and shows the following output.

 

 

Local Variables (Method Level Scope)

These are the variables that are declared inside a method, constructor, or block have a method-level or block-level scope and cannot be accessed outside in which it is defined. Variables declared inside a pair of curly braces {} have block-level scope.

Declaring a Variable Inside a Method

 

 

Declaring a Variable Inside a Constructor

 

 

No comments:

Post a Comment