Apex Variables

7 minute read
0
Sfdcpandaschool

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:

  1. local
  2. Instance
  3. Static

There are two types of data types in apex:

  1. Primitive
  2. 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

  1. Local Variable
  2. 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.

  3. Instance Variable
  4. 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.

  5. Static variable
  6. 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

Post a Comment

0Comments
Post a Comment (0)