Tuesday, April 8, 2014

What is Variable and How to create a Variable in Apex?

What is Variable and How to create a Variable 

in Apex?


The variable is the basic unit of storage in any programming language. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime.


Declaring a Variable :- In Apex all variables must be declared before they can be used. The basic form of a variable. declaration is shown here:


type identifier [ = value][, identifier [= value] ...] ;

Integer i = 0;
String str;
Account a;
Account[] accts;
Set<String> s;
Map<ID, Account> m;

All variables allow null as a value and are initialized to null if they are not assigned another value. For instance, in the following example, i, and k are assigned values, while j is set to null because it is not assigned:

Integer i = 0, j, k = 1;

Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cannot 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++);

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:

Integer I;
//Integer i; This would be an error.

• References to object and field names are case insensitive. For example:
Account a1;
ACCOUNT a2;

• SOQL and SOSL statements are case insensitive. For example:
Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];

Constants :- Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. For example:

public class myCls {
  static final Integer PRIVATE_INT_CONST;
  static final Integer PRIVATE_INT_CONST2 = 200;
  public static Integer calculate() {
    return 2 + 7;
  }
  static {
   PRIVATE_INT_CONST = calculate();
  }
}




0 comments:

Post a Comment

 
| ,