APEX Tutorial | Salesforce Apex Basics

Salesforce Apex Tutorial : Apex is an object-oriented and strongly typed programming language developed by Salesforce for building Software as a Service (SaaS) and Customer Relationship Management (CRM). Using Apex Programming Language developers can execute flow and transaction control statements. Salesforce Apex syntax is similar to Java and acts like database stored procedures. Apex helps developers to create third-party SaaS applications and add business logic to system events by providing back-end database support and client-server interfaces.

Apex helps developers to add business logic to the system events like button clicks, related record updates, and Visualforce pages. Apex has a similar syntax to Java.

In this beginner Salesforce Apex tutorial, you will learn Apex basics like-

Features of Apex Programming Language

Here are the important features of Salesforce Apex:

  • Apex is a case insensitive language.
  • You can perform DML operations like INSERT, UPDATE, UPSERT, DELETE on sObject records using apex.
  • You can query sObject records using SOQL(salesforce object query language) and SOSL(salesforce object search language) in apex.
  • Allows you to create a unit test and execute them to verify the code coverage and efficiency of the code in apex.
  • Apex executes in a multi-tenant environment, and Salesforce has defined some governor limits that prevent a user from controlling the shared resources. Any code that crosses the salesforce governor limit fails, an error shows up.
  • Salesforce object can be used as a datatype in apex. For example –
    Account acc = new Account(); 

    ,here Account is a standard salesforce object.

  • Apex automatically upgrades with every Salesforce release.

When Should Developer Choose Apex

Apex code should only be written if a business scenario is too complex and can’t be implemented using the pre-built functionality provided by Salesforce.

Following are the few scenarios where we need to write apex code:

  • To create web services that integrate Salesforce with other applications.
  • To implement custom validation on sobjects.
  • To execute custom apex logic when a DML operation is performed.
  • To implement functionality that can’t be implemented using existing workflows flows and process builders functionality.
  • To setup email services, you need to include processing the contents, headers, and attachments of email using apex code.

Working Structure Of Apex

Now in this Apex tutorial, we will learn about working structure of Apex:

Following are the flow of actions for an apex code:

  • Developer Action: All the apex code written by a developer is compiled into a set of instructions that can be understood by apex runtime interpreter when the developer saves the code to the platform and these instructions then save as metadata to the platform.
  • End User Action: When the user event executes an apex code, the platform server gets the compiled instructions from metadata and runs them through the apex interpreter before returning the result.

Apex Syntax

Variable Declaration:

As apex is strongly typed language, it is mandatory to declare a variable with datatype in apex.

contact con = new contact();

here the variable con is declared with contact as a datatype.

SOQL Query:

SOQL stands for Salesforce Object Query Language. SOQL is a querying language that enables users to query and retrieve data from the salesforce database. It is similar to SQL, with few differences SOQL queries are used to fetch sObject records from Salesforce database.

Account acc = [select id, name from Account Limit 1];

The above query fetches account record from salesforce database.

Loop Statement:

Loop statement is used to iterate over the records in a list. The number of iteration is equal to the number of records in the list. For example:

list<Account>listOfAccounts = [select id, name from account limit 100];
// iteration over the list of accounts
for(Account acc : listOfAccounts){

In the above snippet of code, listOfAccounts is a variable of list datatype.

Flow Control Statement:

Flow control statement is beneficial when you want to execute some lines of the code based on some conditions.

list<Account>listOfAccounts = [select id, name from account limit 100];
// execute the logic if the size of the account list is greater than zero
if(listOfAccounts.size() >0){
	//your logic

The above snippet of code is querying account records from the database and checking the list size.

DML statement:

DML stands for data manipulation language. DML is a series of statements and methods available in Apex that enable a developer to push data changes to the Salesforce database.

Account acc = new Account(Name = ‘ Test Account’);
Insert acc; //DML statement to create account record.

Apex Development Environment

Now in this Salesforce Apex tutorial, we will learn about Apex Development Environment:

Apex code can be developed either in sandbox and developer edition of Salesforce. It is a best practice to develop the code in the sandbox environment and then deploys it to the production environment.

Apex code development tools: Following are the three tools available to develop apex code in all editions of Salesforce.

  • Force.com Developer Console
  • Force.com IDE
  • Code Editor in the Salesforce User InterfaceYou
Salesforce APEX Tutorial
APEX Tutorial | Salesforce Apex Basics 2

Data Type in Apex

Following are the datatypes supported by apex:


Primitive data types are the foundational data types that are used to hold Integer, Double, Long, Date, Date Time, String, ID, and Boolean. All primitive data types are passed by value, not by reference. We define a variable with a primitive data type using the following syntax

DataType variableName = value;


There are number of ways in which we can invoke apex, but mostly we use triggers. Three types of collection are available in Apex

  • List: A list in Apex is similar to Arrays in other programming Languages. It is an ordered collection of primitives, sObjects, collections, or Apex objects based on indices.
  • Set: An unordered collection of unique primitives. Sets are collections of unique elements with no duplicates. we declare a set using the Set keyword.
  • Map: Maps are the collection of key-value pairs that allows us to store a variety of data types using a key of any data type. It is collection of unique, primitive keys that map to single values which can be primitives, sObjects, collections, or Apex objects.


sObject means Salesforce Object, it is a special data type in Salesforce. It is similar to a table in SQL and contains fields which are similar to columns in SQL. sObject is the base data type for any standard or custom object in Salesforce, and from this data type we get specific instances of object types for our custom and standard objects.


An Enum allows user to define a preset list of identifiers for this abstract type that can be used. Enum is an abstract data type that stores one value of a finite set of specified identifiers Classes. We define enum using the enum keyword.

Objects :

It refers to any data type which is supported in Apex.


Apex Access Specifier

Following are the access specifier supported by apex:


A public access modifier declares that this class is visible to any code within the application or namespace. This access specifier gives access to a class, method, variable to be used by an apex within a namespace.


A class designated private can not be called outside of the class that they are define within. This access specifier gives access to a class, method, variable to be used locally or within the section of code, it is defined. All the technique, variables that do not have any access specifier defined have the default access specifier of private.


This access specifier gives access to a method, variable to be used by any inner classes within defining Apex class.


This access specifier gives access to a class, method, variable to be used by an apex within a namespace as well as outside of the namespace. It is a best practice not to used global keyword until necessary. This is useful for when we are wanting to expose our code as a SOAP web service.

Keywords in Apex

With sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is enforced and if this keyword is absent, then code executes under system context.

public with sharing class MyApexClass{
// sharing rules enforced when code in this class execute

Without sharing:

If a class is defined with this keyword, then all the sharing rules apply to the current user is not enforced.

public without sharing class MyApexClass{
// sharing rules is not enforced when code in this class execute


A variable, Method is defined with the static keyword is initialized once and associated with the class. Static variables, methods can be called by class name directly without creating the instance of a class.


A constant, Method is defined with the final keyword can’t be overridden.

public class myCls {
static final Integer INT_CONST = 10;

If you try to override the value for this INT_CONST variable, then you will get an exception – System.FinalException: Final variable has already been initialized.


This keyword returns a value from a method.

public String getName() {
return  'Test' ;


It defines a null constant and can be assigned to a variable.

Boolean b =null;


If a class is defined with a virtual keyword, it can be extended and overridden.


If a class is defined with abstract keyword, it must contain at least one method with keyword abstract, and that method should only have a signature.

public abstract class MyAbstrtactClass {
abstract Integer myAbstractMethod1();

Apex String

A string is a set of characters with no character limits.

String name = 'Test';

There are several in-built methods provide by String class in salesforce. Following are the few frequently and mostly used functions:


This method truncates a string to the specified length and returns it if the length of the given string is longer then specified length; otherwise, it returns the original string. If the value for maxWidth variable is less than 4, this method returns a runtime exception – System.StringException: Minimum abbreviation width is 4

String s = 'Hello World';
String s2 = s.abbreviate(8);
System.debug('s2'+s2); //Hello...


This method converts the first letter of a string to title case and returns it.

String s = 'hello;
String s2 = s.capitalize();
System.assertEquals('Hello', s2);


This method returns true if the String calling the method contains the substring specified.

String name1 = 'test1';
String name2 = 'test2';
Boolean flag = name.contains(name2);
System.debug('flag::',+flag); //true


This method returns true if the parameter passed is not null and indicates the same binary sequence of characters as the string that is calling the method.

While comparing Id values the length of the ID’s may not to be equal. For example: if a string that represents 15 characters id is compared with an object that represents 18 characters ID this method returns true.

Id idValue15 = '001D000000Ju1zH';
Id idValue18 = '001D000000Ju1zHIAR';
Boolean result4 = stringValue15.equals(IdValue18);
System.debug('result4', +result4); //true

In the above example equals method is comparing 15 characters object Id to 18 characters object Id and if both these id represents the same binary sequence it will return true.

Use this method to make case-sensitive comparisons.


This method adds an escape character () before any single quotation in a string and returns it. This method prevents SOQL injection while creating a dynamic SOQL query. This method ensures that all single quotation marks are considered as enclosing strings, instead of database commands.

String s = 'Hello Tom';
system.debug(s); // Outputs 'Hello Tom'
String escapedStr = String.escapeSingleQuotes(s);
// Outputs \'Hello Tom\'


This method removes all the occurrence of the mentioned substring from the String that calls the method and returns the resulting string.

String s1 = 'Salesforce and force.com';
String s2 = s1.remove('force');
System.debug( 's2'+ s2);// 'Sales and .com'


This method returns a substring starts from the character at startIndex extends to the last of the string.

String s1 = 'hamburger';
String s2 = s1.substring(3);
System.debug('s2'+s2); //burger


This Method reverses all the characters of a string and returns it.

String s = 'Hello';
String s2 = s.reverse();
System.debug('s2::::'+s2);// olleH  // Hello

trim(): This method removes all the leading white spaces from a string and returns it.


This method returns the string representation of passed in object.

Apex Governor Limits

For Salesforce developers, the governor limits are good because they make you consider how you are developing your solution in a way that is going to give your user the best experience possible. Salesforce is a web application on which every interaction for the end-user involves some form of callout from a browser or app to the Salesforce servers. So what are Salesforce Apex Governor Limits?

Apex governor limits are the limits enforced by apex runtime engine to ensure that any runway apex code and processes don’t control the shared resources and don’t violate the processing for other users on the multitenant environment. These limits are verified against each apex transaction. Following are the governor limits defined by salesforce on each apex transaction:

SOQL queries that can be done in a synchronous transaction100
SOQL queries that can be done in an Asynchronous transaction200
Records that can be retrieved by a SOQL query50000
Records that can be retrieved by Database.getQueryLocator10000
SOSL queries that can be done in an apex transaction20
Records that can be retrieved by a SOSL query2000
DML statements that can be done in an apex transaction150
Records that can be processed as a result of a DML statement, Approval.process, or database.emptyRecycleBin10000
Callouts that can be done in an apex transaction.100
Cumulative timeout limit on all the callouts that are being performed in an apex transaction120 seconds
Limit on apex jobs that can be added to the queue with System.enqueueJob50
Execution time limit for each Apex transaction10 minutes
Limit on characters that can be used in an apex class and trigger1 million
CPU time limit for synchronous transaction10,000 milliseconds
CPU time limit for asynchronous transaction60,000 milliseconds

Apex Getter and Setter

Apex property is similar to apex variable. Getter and setter are necessary to an apex property. Getter and setter can be used to execute code before the property value is accessed or changed. The code in the get accessor executes when a property value is read. The code in the set accessor runs when a property value is changed. Any property having get accessor is considered read-only, any property having set accessor is considered to write only any property having both get and set accessor is deemed to be read-write. Syntax of an apex property:

public class myApexClass {
// Property declaration
	access_modifierreturn_typeproperty_name {
	get {

Here, access_modifier is the access modifier of the property. return_type is the dataType of the property. property_name is the name of the property.

Below is an example of an apex property having both get and set accessor.

public class myApex{
	public String name{
		get{ return name;}
		set{ name = 'Test';}

Here, the property name is name, and it’s public property, and it is returning a string dataType.

It is not mandatory to have some code in the get and set block. These block can be left empty to define an automatic property. For example:

public double MyReadWriteProp{ get; set; }

Get and set accessor can also be defined with their access modifier. If an accessor is defined with a modifier, then it overrides the access modifier for the property.

public String name{private get; set;}// name is private for read and public to write

Apex Class

An apex class is a blueprint or template from which objects are created. An object is the instance of a class.There are three ways of creating apex classes in Salesforce:

  • Developer Console
  • Force.com IDE
  • Apex class detail page.

In apex, you can define an outer class also called top-level class, and you can also define classes within an outer class called inner classes. It is mandatory to use access modifier like global or public in the declaration of the outer class. It is not necessary to use access modifier in the declaration of inner classes.

An apex class is defined using class keyword followed by the class name.

Extends keyword is used to extend an existing class by an apex class, and implements keyword is used to implement an interface by an apex class.

Salesforce Apex doesn’t support multiple inheritances, an apex class can only extend one existing apex class but can implement multiple interfaces.

An apex class can contain user-defined constructor, and if a user-defined constructor is not available, a default constructor is used. The code in a constructor executes when an instance of a class is created.

Syntax of the Apex Class example:

public class myApexClass{
// variable declaration
	public myApexClass{
//methods declaration

The new keyword is used to create an instance of an apex class. Below is the syntax for creating an instance of a apex class.

myApexClass obj = new myApexClass();

Apex Trigger

Apex triggers enable you to execute custom apex before and after a DML operation is performed.

Apex support following two types of triggers:

Before triggers: These triggers are used to validate and update the field’s value before the record save to the database.

After triggers: These triggers are used to access the fields(record ID, LastModifiedDate field) set by the system after a record committed to the database. These fields value can be used to modify other records. Records that fires after triggers are read-only.

It is a best practice to write bulky triggers. A bulky trigger can process a single record as well as multiple records at a time.

Syntax of an apex trigger:

trigger TriggerName on ObjectName (trigger_events) {

Here, TriggerName is the name of the trigger, ObjectName is the name of the object on which trigger to be written, trigger_events is the comma-separated list of events.

Following are the events supported by the apex triggers: before insert, before the update, before delete, after insert, after an update, after delete, after undelete.

Static keywords can’t be used in an Apex trigger. All the keywords applicable to inner classes can be used in an Apex trigger.

There are implicit variable define by every trigger that returns the run-time context. These variables are defined in the system. Trigger class. These variables are called context variables. Below screenshot shows the context variable supported by apex trigger.

Following are the consideration of the context variable in the apex trigger:

  • Don’t use the trigger.new and trigger.old in DML operations.
  • Trigger.new can’t be deleted.
  • Trigger.new is read-only.
  • Trigger.new can be used to changes the values of the fields on the same object in before trigger only.

Below screenshots list the considerations about specific actions in different trigger events.

Batch Class in Apex

Batch class in salesforce is used to process a large number of records that would exceed the apex governor limits if processed normally. Batch class executes the code asynchronously.

Following are the advantages of batch class:

  • Batch class process the data in chunks and if a chunk fails to process successfully, all the chunks successfully processed do not roll back.
  • Every chunk of data in a batch class processed with a new set of governor limits which ensure that code executes within the governor execution limits.
  • Database. Batchable interface must be implemented by an apex class to be used as a batch class. It provides three methods which must be implemented by the batch class.

Following are the three methods provided by Database. Batchable interface:


This method generates the scope of records or objects to be processed by the interface method execute. During the execution of batch, it is called once only. This method either returns a Database.QueryLocator object or an Iterable. The number of records retrieved by SQL query using the Database.QueryLocator object is 50 million records but using an iterable, the total number of records that can be retrieved by the SQL query is 50000 only. Iterable is used to generate complex scope for batch class.

Syntax of start method:

global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {}


This method is used for the processing of each chunk of data. For each chunk of records execute method is called. The default batch size for execution is 200 records. Execute method takes two arguments:

A reference to the Database.BatchableContext object,

A list of sObjects, such as List<sObject>, or a list of parameterized types. Syntax of execute method:

global void execute(Database.BatchableContext BC, list<P>){}


The finish method is called once during the execution of the batch class. Post-processing operations can be performed in the finish method. For example: sending the confirmation email. This method is called when all the batch get processed. Syntax of Finish method:

global void finish(Database.BatchableContext BC){}

Database.BatchableContext object:

Each method of the Database. Batchable interface has a reference to Database.BatchableContext object.

This object is used to track the progress of the batch job.

Following are instance methods provided by BatchableContext :

  • getChildJobId(): This method returns the ID of a batch job that is currently processed.
  • getJobId(): This method returns the ID of the batch job.

Below is the syntax of a batch class :

global class MyBatchClass implements Database.Batchable<sObject> {
	global (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContextbc) {
// collect the batches of records or objects to be passed to execute
global void execute(Database.BatchableContextbc, List<P> records){
// process each batch of records
global void finish(Database.BatchableContextbc){
// execute any post-processing operations

Database.executeBatch Method:

Database.executeBatch method is used for executing a batch class.

This method takes two parameters: Instance of the batch class to be processed, Options parameter to specify the batch size if not specified it takes the default size of 200.

Syntax of Database.executeBatch :


Executing a batch class name MyBatchClass :

MyBatchClassmyBatchObject = new MyBatchClass(); 
Id batchId = Database.executeBatch(myBatchObject,100);

Database.stateful :

Batch class is stateless by default. Every time the execute method is called a new copy of an object is received, all the variables of the class is initialized.

Database.stateful is implemented to make a batch class stateful.

If your batch class implemented the Database, stateful interface all the instance variable retain their values, but the static variables get reset between the transaction.

Scroll to Top