Question: Describe local and global variable with example.
What is a Variable?
Definition of Local Variable
Example of Local Variable:
Definition of Global Variable:
Example of Global Variable:
What is a Variable?
Variable is a name assign to a storage area that the program can manipulate. A variable type determines the size and layout of the variable's memory.
It also determines the range of values which need to be stored inside that memory and nature of operations that can be applied to that variable.
Definition of Local Variable
A local variable is a type of variable declared within programming block or subroutines. It can only be used only inside that subroutine or code block in which they were declared. The local variable exists until the block of the function is in under execution. After that, it will be destroyed automatically.
Example of Local Variable:
public int add(){Here, 'a' and 'b' are local variables
int a =4;
int b=5;
return a+b;
}
Definition of Global Variable:
Global variables are defined outside of a subroutine or function. The global variable will hold its value throughout the lifetime of a program. They can be accessed within any function defined for the program.
Example of Global Variable:
int a =4;Here, 'a' and 'b' are global variables.
int b=5;
public int add(){
return a+b;
}