Variables in Apex

When it comes to variable declaration in apex , it is similiar to Java. Both languages share similar syntax for defining local variables. Let’s explore some examples to illustrate how to declare local variables in each language.

    
String productName = 'HCL';
Integer i = 0;
Set setOfProducts = new Set();
Map mapOfProductIdToName = new Map();
    

Note that all the variables are assigned with the value null.

Declaring Variable

We can declare the variables in Apex like String and Integer as follows −

    
String strName = 'My String';  //Declaring String variable
Integer myInteger = 1;         //Declaring Integer variable
Boolean mtBoolean = true;      //Declaring Boolean variable
    

Scope of Variables

In Apex, a variable is valid only from the point where it is declared. This means you cannot redefine the same variable within the same code block. Also, if you declare any variable in a method, then that variable scope will be limited to that particular method only. However, class variables are accessible throughout the entire class .

Example –

    
//Declare variable 
List Products = new List();
Products.add('Pen');

//You cannot declare this variable in this code clock or sub code block again
//If you do so then it will throw the error as the previous variable in scope
//Below statement will throw error if declared in same code block
List Products = new List();