Apex Variables in Salesforce
A variable is a container which holds the value while the Apex program is executed. A variable is a name of a memory location which internally holds a memory location. This is why it is assigned a data type, so that we can inform the memory what type of data this memory location is going to store, as well as the size of the allocated memory.
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
A variable is a name of a reserved area allocated in memory (RAM). In other words, it is a name of a memory location. The value of a variable can be changed.
Integer i = 100;
Types of Variables
There are three types of variables in Apex:
- Local Variable: A variable declared inside the body/scope of the method is called a local variable. You can use this variable only within that method or, in other words, you can say the scope of that method only, and the other methods in the class are not even aware that the variable exists. Note: A local variable can never be defined with the “static” keyword.
- Instance Variable: A variable declared inside the class but outside the body/scope of the method is called an instance variable. It is also not declared as static. It is called an instance variable because its value is instance-specific and is not shared among instances.
- Static Variable: A variable which is declared as static is known as a static variable. It cannot be defined as local. It creates a single copy of the static variable and shares it among all the instances of the same class. Memory allocation for a 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
0 Comments