Newer Version Available
Variables
For example:
1Integer i = 0;
2String str;
3List<String> strList;
4Set<String> s;
5Map<ID, String> m;As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
1Integer i, j, k;Variable Naming Rules
When naming variables, follow these rules.
- Variable names are case-insensitive.
- Variable names can contain only letters (A-Z or a-z), numbers (0-9), and underscores (_). Spaces and other special characters, including dollar signs ($) and hyphens (-), aren’t allowed.
- Variable names must begin with a letter (A-Z or a-z). Names can’t begin with a number (0-9) or an underscore (_).
- Variable names can’t end with an underscore (_).
- Varable names can’t contain consecutive underscores (_ _).
- Reserved keywords can’t be used as variable names.
- Variable names can have a maximum length of 255 characters.
- Salesforce doesn't recommend sharing the same name between a variable and either its class or a method in its class, although it is permitted to do so.
Null Variables and Initial Values
1Boolean x = null;
2Decimal d;1Date d;
2d.addDays(2);All variables are initialized to null if they aren’t assigned a value. For instance, in the following example, i, and k are assigned values, while the integer variable j and the boolean variable b are set to null because they aren’t explicitly initialized.
1Integer i = 0, j, k = 1;
2Boolean b;Variable Scope
Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
1Integer i;
2{
3 // Integer i; This declaration is not allowed
4}
5
6for (Integer j = 0; j < 10; j++);
7for (Integer j = 0; j < 10; j++);Case Sensitivity
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:
- Variable and method names are case-insensitive. For
example:
1Integer I; 2//Integer i; - References to object and field names are case-insensitive. For
example:
1Account a1; 2ACCOUNT a2; - SOQL and SOSL statements are case- insensitive. For
example:
1Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];
Also note that Apex uses the same filtering semantics as SOQL, which is the basis for comparisons in the SOAP API and the Salesforce user interface. The use of these semantics can lead to some interesting behavior. For example, if an end-user generates a report based on a filter for values that come before 'm' in the alphabet (that is, values < 'm'), null fields are returned in the result. The rationale for this behavior is that users typically think of a field without a value as just a space character, rather than its actual null value. Consequently, in Apex, the following expressions all evaluate to true:
1String s;
2System.assert('a' == 'A');
3System.assert(s < 'b');
4System.assert(!(s > 'b'));