About Scope of Variables (ASV)


ASV:   SOLD       




In addition to a variable name and data type, a variable has a scope. The scope determines where the program can access the variable. The scope also determines the lifetime of a variable or how long the variable remains in memory. The scope is determined by where the variable declaration is placed in the program.

To simplify it, try to think of any range between the curly braces {.....}, outside the curly braces is called the outer block, and inside the curly braces is called the inner block.

If you declare variables in an outer block, they will be visible (i.e., usable) by the inner block, however, if you declare variables in an inner block, you cannot expect the outer block to see them.

A variable's range within a block where, once declared, it starts from the point where the variable is declared, and is in the inner block.

Example, given a code snippet;


Variable Scope

The code we have here has five ranges marked by lines and captions that represent that range, with variables i, j, k, m and n, and 5 ranges A, B, C, D and E, we have the following variable ranges:

  • The range of variable i is A.
  • The range of variable j is B.
  • The range of variable k is C.
  • The range of variable m is D.
  • The range of variable n is E.

Now, given both the main and test methods in our previous example,


Variable Range

In the first method, the Range variables are;

ages[ ] - scope A
i in B - scope B
i in C - scope C

In the test method, the Range variables are;

arr[ ] - scope D
i in E - scope E

When a variable is declared, only one variable is identified or the name can be identified in the range, meaning if you have the following declaration;

{
int test = 10;
int test = 20;
}

Your compiler will throw an error because you need to have different names for variables in one block, however, you can have two variables with the same name, if they are not declared in the same block, Example;

int test = 0;
System.out.print( test );
//..some code here
{
int test = 20;
System.out.print( test );
}

When the first system out.print is called, it prints the value of the first test variable since it is in the range of that variable. The second, system.out print, prints the value 20 since it is closed in the range of that variable.

Program Writing Guide: Avoid giving the same name to variables to avoid confusion!


Post a Comment

Previous Next

نموذج الاتصال