Newer Version Available
Variables
Local variables are declared with Java-style syntax. 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;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; This would be an error. - 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'));