A variable is a container which holds the value while the Apex program is executed. Actually a variable is a name of memory location which internally hold a memory location that is why it assigned with a data type, so that we can tell to memory that what type of data this memory location is going to store in it as well as size of the allocated .
There are three types of variables in apex:
- local
- Instance
- Static
There are two types of data types in apex:
- Primitive
- Non-Primitive.
Variable in depth
Variable is name of reserved area allocated in memory i.e. RAM. In other words, we can say it is a name of memory location. Variable value can be changed.
Integer i = 100;
Types of Variables
There are three types of variables in apex:
o local variable
o instance variable
o static variable
- Local Variable
- Instance Variable
- Static variable
A variable declared inside the body/scope of the method is called local variable. You can use this variable only within that method or in other words you can say scope of that method only and the other methods in the class are not even aware that the variable exists.
Note : A local variable never be defined with “static” keyword.
A variable declared inside the class but outside the body/scope of the method, is called instance variable. It is also not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
A variable which is declared as static is known static variable. It cannot be defined as local. It creates a single copy of static variable and share among all the instances of the same class. Memory allocation for static variable happens only once when the class is loaded into the memory.
Types of variables in apex with example for better understanding
public class VariableDemo { integer i=100; //instance variable static integer j =200; //static variable void fun(){ integer k=300;//local variable } // end of method } //end of class scope
Apex Variable Example: Adding Two Numbers:
public class Addition { public void doAdd() { integer a = 10; integer b = 20; integer res = a+b; System.debug(res); // this statement is used to print on console } }
Output:
30