Local Variable & Global Variable
This article focuses on below contents:
- What is variable & its types?
- Declaration and Initialization of variable
- What is Local Variable with example?
- What is Global Variable with example?
Let us see in detail:
1. What is variable?
Variable is a named memory location which can store some value & it can change n no. of times during execution.
Variables are classified into two types:
- Local Variable
- Global Variable
2. Declaration & Initialization of Variable:
Syntax of Variable Declaration:
datatype variable_name;
Example : int a;
Syntax of Variable Initialization:
variable_name=value;
Example : a=30;
Variable can be declared and initialized in a single line.
datatype variable_name=value;
Example : int a=20;
3. What is Local Variable with example?
Any variable which is declared within the methods is called as Local variable. The scope of the local variable is within the methods or from the beginning of the method till the end of the method.
Local variables will not have default values. They cannot be classified as static and non static. They can be utilized until and unless they are initialized else compile time error will be thrown.
Example:
4. What is Global Variable with example?
Any variable which is declared outside the method ,inside the class is called as Global variable.
The scope of the Global variable is within the class or from the beginning of the class till the end of the class. Global variables will have default values. They can be classified into static and non-static.
Once the global variable is declared and cannot initialize in the next line but we can initialize inside the method.
Example:
Happy Blogging!!!!!!!