Tuesday, December 11, 2012

Data Types in Apex Programming Language

Apex is a strongly typed, object-oriented programming language. Just like any other programming language, Apex has variety of data types that you can use. Let us see that list in this article.

Primitive Types - This data types include String, Integer, Long, Double, Decimal, ID, Boolean, Date, Datetime, Time and Blob. All these data type variables are always passed by value in methods.  Another point to note is in Apex, all variables are initialized to null when declared. You must explicitly initialize to non-null values before using.

sObject Types - This is a special data type in Apex. sObject is a generic data type for representing an Object that exists in Force.com. It could be Standard object like Account, Opportunity etc., or Custom object that you define.  Following are some of the examples of sObject variables -

    sObject s = new Account();
    Account a = new Account();
    CustomO__c c = new CustomO__c();

As you can see above, your custom objects have an extension of __c to distinguish from the Force.com standard objects. Fields from the sObject variable can be accessed using the dot notation. For example,
        
    a.Name = 'ABC Corp';

Collections - Apex has 3 types of collections. Lists, Sets and Maps.
  • A list is like an array, a sequential collection of elements with first index position as zero. List can contain elements of primitive types, sObjects, user-defined objects, Apex objects or even other collections. A list can contain up to four levels of nested collections. List can contain duplicate elements.
  • A set is also a collection of elements and elements can be of any data type. Unlike list, set contains unique elements and elements in set are not in any specific order. 
  • A map is a collection of key-value pairs. Keys and values can be any data type. Keys are unique and map elements must be accessed by the key as the order of  map elements are not reliable.
Enums - Just like in other programming languages, Enum type represents a fixed set of named constants. 

Apex variables can be objects created from user defined Apex classes or objects created from  system supplied Apex classes as well.

Happy cloud computing using Salesforce!

No comments:

Post a Comment