Variable Scope
This is a program that will tell you about the scope of variables in different parts of programs.
Learning Objectives
To learn java concepts related to :
- Blocks
- Variable Scope
- Declaration and initialization instance variables.
Program Approach
The objective is to demonstrate the scope of a variable and the advantages of blocks in a java program. We will be declaring a variable outside the main() method. Then we will be initializing it within the main() method and performing calculations with it.
Source Code
|
Run Output
Code Understanding
static int n;
Here, we have declared the variable outside the main method() but within the class. So we can initialize the variable inside the main method() and we can also perform calculation with it without any loss of ambiguity. We can use the variable n in any part of the class without declaring it again and again but while going from one block to another block we can change the value of the variable and therefore the value of the variable will be different for each block .
Note : A variable can be left uninitialized only and only if it is an instance or a class variable but if we are declaring a local variable it becomes mandatory to set it with an initial value or the compiler will throw an error and the program will not be executed
System.out.println(“The square of the number is :”+(n*n));
In the above two statements we have used the variable a inside the main() method although they have been initialized outside the main method and there was no error found. This is because the variable which has been declared inside a block can be used in all other blocks declared inside that block.
Notes
{} square bracket actually denote a block. The square bracket for the class are a block in which another block depicted by block of main method is there. Every block has its own set of variables and in a different block same names of variables can be repeated, provided they have not been declared in the outside block of class scope.
Suggested Filename(s): VariableScope.java
admin| Created: 16-Aug-2016 | Updated: 21-Mar-2018|