Local variables are declared with Java-style syntax. For example:
Integer i = 0; String str; List<String> strList; Set<String> s; Map<ID, String> m;
As with Java, multiple variables can be declared and initialized in a single statement, using comma separation. For example:
Integer i, j, k;
Boolean x = null; Decimal d;
Date d;
d.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.
Integer i = 0, j, k = 1; Boolean b;
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:
Integer i; { // Integer i; This declaration is not allowed } for (Integer j = 0; j < 10; j++); for (Integer j = 0; j < 10; j++);
To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:
Integer I; //Integer i; This would be an error.
Account a1; ACCOUNT a2;
Account[] 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:
String s; System.assert('a' == 'A'); System.assert(s < 'b'); System.assert(!(s > 'b'));