Process Automation and Logic · Topic 2 of 7

Apex Language Basics and Control Flow

Apex data types, collections, constants, access modifiers, static and instance members, interfaces, and control flow with if, switch and loops.

  • 4 min
In a nutshell
  • Uninitialized variables are null, even Integers and Booleans.
  • List is ordered, Set is unique, Map is key to value; a Map can be built from a query.
  • private is the default modifier; global is the widest.

What it is

Apex is Salesforce's strongly typed, object-oriented language, with syntax close to Java. Code lives in classes and triggers, runs on Salesforce servers and is case-insensitive.

The exam expects you to read short Apex snippets and predict what they do, so the basics matter: types, collections, modifiers, interfaces and loops.

Variablestypes and collectionsMethodsstatic or instanceClassesmodifiers, interfacesControl flowif, switch, loops

How it works

Data types

KindExamples
PrimitivesInteger, Long, Decimal, Double, String, Boolean, Date, Datetime, Time, Id, Blob
sObjectsAccount, Invoice__c, or the generic SObject
CollectionsList<T> (ordered), Set<T> (unique), Map<K, V> (key to value)
Enumspublic enum Season { WINTER, SUMMER }

An uninitialized variable is null, including Integers and Booleans. Calling a method on null throws a NullPointerException. The safe navigation operator ?. returns null instead.

List<Account> accs = new List<Account>();
Set<Id> ids = new Set<Id>();
Map<Id, Account> byId = new Map<Id, Account>([SELECT Id, Name FROM Account LIMIT 10]);
Account acc;                       // null until assigned
String name = acc?.Owner?.Name;   // null if acc or Owner is null

A Set removes duplicates, which makes it the standard holder for Ids collected in a trigger. A Map built from a query gives fast lookup by Id.

Constants and modifiers

public class Pricing {
    public static final Decimal VAT_RATE = 0.20;   // constant
    private Integer count;                          // instance, private by default
    public static Integer calls = 0;                // static: one per transaction
}
Access modifierVisible to
private (default)The defining class only
protectedThe class, inner classes and subclasses
publicCode in the same namespace (your org or package)
globalAll code, including other namespaces; needed for some managed package and web service use
Other keywordMeaning
staticBelongs to the class; a static variable lasts for the whole transaction
finalValue set once
virtualCan be extended or overridden
abstractMust be extended; can hold abstract methods
overrideReplaces a virtual or abstract method
with sharing / without sharing / inherited sharingRecord sharing rules applied or not

Interfaces

A class implements an interface and must define all its methods.

InterfaceUsed for
Database.Batchable<sObject>Batch Apex: start, execute, finish
QueueableQueueable jobs: execute(QueueableContext)
SchedulableScheduled jobs: execute(SchedulableContext)
Database.StatefulKeep instance variables across batch execute calls
ComparableCustom sort order with compareTo
HttpCalloutMockFake HTTP responses in tests

Control flow

Integer score = 0;
for (Integer i : new List<Integer>{1, 2, 3, 4, 5}) {
    switch on i {
        when 1, 2 { score += 1; }
        when 3 { score += 10; }
        when else { score += 100; }
    }
}
System.debug(score);   // 212
ConstructNotes
if / else if / elseStandard branching
switch onWorks on Integer, Long, String, sObject type and enum; when else is the default
for (init; condition; step)Traditional loop
for (Account a : accs)List or set iteration
for (List<Account> chunk : [SELECT ...])SOQL for loop in chunks of 200
while / do ... whiledo while runs the body at least once
break / continueLeave the loop or skip to the next iteration

A worked example

What does this print?

Integer total = 0;
Integer i = 5;
do {
    total += i;
    i--;
} while (i > 5);
System.debug(total);

The body runs once before the condition is checked, so total is 5. A while (i > 5) loop would not run at all and would print 0.

Exam tip

In code questions, trace each loop by hand with a small table of variable values. Most traps are off-by-one or a do while that runs once.

How the exam asks about this

  • "Collect unique Account Ids from 200 contacts." Set<Id>.
  • "Keep a value for the whole transaction across trigger runs." A static variable.
  • "Run code at 2 a.m. every day." A class implementing Schedulable.

What to remember for the exam

  • Uninitialized variables are null, even Integers and Booleans.
  • List is ordered, Set is unique, Map is key to value; a Map can be built from a query.
  • private is the default modifier; global is the widest.
  • Static variables last for one transaction, not across transactions.
  • switch on uses when and when else; do while runs at least once.
Watch out

Apex strings compare with == case-insensitively. Use equals() when case matters.

Common mistakes

Expecting a static variable to survive between transactions. It resets at the start of each one.

Using a List to collect Ids for a query filter. A Set avoids duplicates.

Forgetting null. Integer count; followed by count++ throws a NullPointerException.

Check yourself

  • What is the default access modifier for an Apex method?

    private.

  • Which interface must a class implement to run as a scheduled job?

    Schedulable, with an execute(SchedulableContext sc) method.

  • How long does a static variable keep its value?

    For the rest of the current transaction only.

Topic 2 of 7 in Process Automation and Logic

Test yourself on Process Automation and Logic

The full Salesforce Platform Developer question bank has 645 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by Salesforce. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.