Apex - Variáveis

Java e Apex são semelhantes em muitos aspectos. A declaração de variável em Java e Apex também é praticamente a mesma. Discutiremos alguns exemplos para entender como declarar variáveis ​​locais.

String productName = 'HCL';
Integer i = 0;
Set<string> setOfProducts = new Set<string>();
Map<id, string> mapOfProductIdToName = new Map<id, string>();

Observe que todas as variáveis ​​são atribuídas com o valor null.

Declaring Variables

Você pode declarar as variáveis ​​no Apex como String e Integer da seguinte maneira -

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

Apex variables are Case-Insensitive

Isso significa que o código fornecido a seguir gerará um erro, pois a variável 'm' foi declarada duas vezes e ambas serão tratadas como iguais.

Integer m = 100;
for (Integer i = 0; i<10; i++) {
   integer m = 1; //This statement will throw an error as m is being declared
   again
   System.debug('This code will throw error');
}

Scope of Variables

Uma variável Apex é válida a partir do ponto em que é declarada no código. Portanto, não é permitido redefinir a mesma variável novamente e no bloco de código. Além disso, se você declarar qualquer variável em um método, esse escopo de variável será limitado apenas a esse método específico. No entanto, as variáveis ​​de classe podem ser acessadas em toda a classe.

Example

//Declare variable Products
List<string> Products = new List<strings>();
Products.add('HCL');

//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<string> Products = new List<strings>();