A variable is a name we assign to a memory location to store values in a computer program. The name given should follow the programming semantics such as a,b,c,x,y,z, sub, div, total, avg, etc.
A variable is a value that can change, dependent on certain conditions or information being passed through a program. Variables are commonly used as a memory to store data to be referenced or manipulated later when the need arises. By referring to the term variable, in computer programming, most commonly, we refer to a memory location. Or, in general, we can say a variable is a named unit of data assigned a value. Even by changing the deal, the name remains the same.
A global variable is a variable that exists outside the function or the subroutine. It has an international scope, meaning it exists until the program runs. It is accessible by any process within the entire program. It’s like a master file that any department can retrieve.
Global Variable Example:
int a =4;
int b=5;
public int add(){
return a+b;
}
Here, ‘a’ and ‘b’ are global variables.
A local Variable is a type of variable constrained within a programming block. It has no existence outside the boundaries of that specific function, after which it automatically destroys. One can only use it within that particular function or the code block it has been declared. This local variable exists till the position exists.
Local Variable Example
public int add(){
int a =4;
int b=5;
return a+b;
}
‘a’ and ‘b’ are local variables here in this function.
Both local variables and global variables are required while programming. However, declaring loads of global variables is unsolicited due to its unwanted changes in the worldwide program.
Discovering the location of the difference can be a cumbersome process. Avoid the creation of any unnecessary global variables.
Cogent Infotech offers great help to new coders writing the codes for the first time. When you begin your programming journey, feel free to connect with our expert consultants.