Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Apex

Learn Apex - 10 Code Examples & CST Typing Practice Test

Apex is a strongly typed, object-oriented programming language developed by Salesforce for building scalable, secure, and automated applications on the Salesforce platform. It allows developers to execute business logic on the server side, integrate external systems, and customize CRM workflows using a syntax similar to Java.

View all 10 Apex code examples →
Apex Counter and Theme ToggleApex Simple AdditionApex FactorialApex Fibonacci SequenceApex Max of Two NumbersApex Array SumApex Even Numbers FilterApex String ConcatenationApex Counter With Loop SimulationApex Conditional Increment

Learn APEX with Real Code Examples

Updated Nov 19, 2025

Explain

Apex runs natively on Salesforce servers and is optimized for multitenant architecture.

It supports asynchronous processing, triggers, and declarative automation integration.

Used to build custom business logic, APIs, batch processes, and advanced CRM customizations.

Core Features

Classes & objects

Triggers for automation

SOQL/SOSL queries

Batch Apex, Queueable Apex, Scheduled Apex

Exception handling & testing framework

Basic Concepts Overview

Classes, methods, and objects

Triggers and automation events

Governor limits

SOQL/SOSL queries

Asynchronous execution (Batch, Future, Queueable)

Project Structure

classes/

triggers/

testClasses/

objects/ (metadata)

lwc/ or aura/ for UI

Building Workflow

Write Apex class or trigger

Run code in Salesforce Developer Console

Deploy using SFDX or Change Sets

Run unit tests

Verify results in org

Difficulty Use Cases

Beginner: simple triggers & queries

Intermediate: batch jobs, API calls

Advanced: complex workflows & async chaining

Expert: large-scale enterprise architectures

Comparisons

Similar syntax to Java

More restricted due to governor limits

Cloud-executed vs local execution

Deep CRM integration unlike general languages

Strict testing requirements

Versioning Timeline

2006 - Apex launched

2010 - Introduction of Batch Apex & async jobs

2013 - API-first enhancements

2018 - Async Queueable Apex

2020-2025 - Modernization: better testing, limits, & packaging

Glossary

SOQL: Salesforce Object Query Language

DML: Data Manipulation Language

Governor Limits: Salesforce resource restrictions

Trigger Context Variables: Execution metadata

SObject: Salesforce data object

Installation Setup

Create Salesforce Developer Org

Install VS Code with Salesforce Extensions

Authorize org using Salesforce CLI

Set up SFDX project directory

Deploy sample Apex classes to org

Environment Setup

Install SFDX CLI

Set up VS Code Salesforce extensions

Connect to dev org

Create scratch org (optional)

Deploy and test sample classes

Config Files

sfdx-project.json

Apex class metadata files

Permission sets

Named credentials

Object metadata XML

Cli Commands

sfdx force:auth:web:login

sfdx force:source:push

sfdx force:apex:test:run

sfdx force:data:soql:query

sfdx force:source:deploy

Internationalization

Apex supports multi-language Salesforce orgs

Labels stored in Custom Labels

Supports UTF-8 strings

Locale-driven formats

Translatable UI via metadata

Accessibility

Developer Console & logs

Step-by-step debug logs

Trailhead courses

Unit testing framework

Salesforce documentation

Ui Styling

Apex does not handle UI directly

Used to supply data to LWC/Aura

Can generate responses for Visualforce

Handles backend logic

UI styling done via LWC/HTML/CSS

State Management

Records stored as SObjects

Static variables for cross-transaction state

Trigger context provides transaction metadata

Platform events store async state

Lists and maps store runtime collections

Data Management

Query via SOQL

Search via SOSL

CRUD via DML

Serialization/deserialization

Integration payload handling

Architecture

Runs on Salesforce multi-tenant architecture

Database interactions via SOQL/SOSL

Triggers executed before/after data operations

Async jobs for long-running tasks

Metadata-driven execution model

Rendering Model

Apex source code compiled on Salesforce

Stored as metadata

Executed in cloud runtime

Integrates with triggers, APIs, events

Runs inside managed multitenant sandbox

Architectural Patterns

Trigger-handler pattern

Service-layer architecture

Repository pattern for SOQL

Async chaining

Platform event-driven workflows

Real World Architectures

Enterprise CRM automations

Healthcare management systems

Banking workflow engines

Sales integrations

SaaS package development

Design Principles

Optimized for multitenancy

Strongly typed Java-like model

Secure execution

Bulk processing support

Metadata-driven workflow

Scalability Guide

Use bulk patterns

Avoid CPU-heavy loops

Use Queueable for large jobs

Use Batch for millions of records

Design reusable service classes

Migration Guide

Move logic from workflows to triggers

Convert Process Builders to Apex (if needed)

Use invocable Apex for Flow

Refactor monolithic triggers into handlers

Move heavy logic to async Apex

Performance Notes

Bulkify all operations

Cache results in maps

Minimize SOQL/DML

Use Queueable for long jobs

Use selective queries

Security Notes

Use WITH SECURITY_ENFORCED in SOQL

Validate user permissions

Enforce CRUD/FLS

Avoid exposing sensitive data in APIs

Use Named Credentials for integrations

Monitoring Analytics

Debug logs

Setup -> Apex Exception Emails

Async job monitoring

Apex Replay Debugger

Event monitoring

Code Quality

Follow trigger-handler pattern

Avoid SOQL/DML inside loops

Use descriptive naming

Write tests for all logic

Use static analysis tools

Practical Examples

Before/after insert trigger

REST API endpoint

Batch job processing thousands of records

Scheduled Apex cleanup

CRUD operations with SOQL

Troubleshooting

Check governor limits

Avoid SOQL inside loops

Use bulkified triggers

Validate API request limits

Monitor async job failures

Testing Guide

Write @isTest classes

Use Test.startTest() & Test.stopTest()

Cover bulk scenarios

Mock callouts using HttpCalloutMock

Maintain 75%+ code coverage

Deployment Options

SFDX CLI

Change Sets

Unlocked Packages

Managed Packages

Metadata API

Tools Ecosystem

Salesforce Developer Console

VS Code with Salesforce Extensions

Salesforce CLI (SFDX)

Workbench

Salesforce Inspector

Integrations

External REST APIs

SOAP integrations

Platform Events

Named Credentials

Salesforce-to-Salesforce

Productivity Tips

Use VS Code shortcuts

Automate deployments with SFDX

Create reusable utility classes

Follow naming conventions

Use logs for debugging

Challenges

Build Lead auto-assignment trigger

Create REST API

Write batch job to process contacts

Integrate with external API

Build managed package logic

Learning Path

Learn Salesforce fundamentals

Master SOQL & DML

Write triggers

Learn async Apex

Integrate external systems

Skill Improvement Plan

Week 1: Apex basics & SOQL

Week 2: Triggers & bulkification

Week 3: Async Apex (Batch/Queueable)

Week 4: Integrations & APIs

Interview Questions

Explain governor limits.

Difference between trigger.new and trigger.old?

What is bulkification?

How do you handle callouts in Apex?

What is a Queueable Apex class?

Cheat Sheet

SELECT Id, Name FROM Account;

insert new Account(Name='Test');

System.debug('Log');

Test.startTest(); ... Test.stopTest();

@future callout=true

Books

Advanced Apex Programming

Salesforce for Developers

Apex Academy Series

Tutorials

Trailhead Apex Basics

Apex Trigger Workshops

Apex Hours YouTube sessions

Official Docs

Salesforce Apex Developer Guide

SOQL & SOSL Reference

Salesforce CLI Reference

Community Links

Salesforce StackExchange

Trailblazer Community

Apex Hours

Community Support

Salesforce StackExchange

Salesforce Trailblazer Community

Apex Hours

Salesforce Discord groups

Local Developer Groups

Monetization

Freelance Salesforce automation

Custom app development

Integration services

Enterprise consulting

AppExchange products

Future Roadmap

Greater async capabilities

More integration support

Better testing tools

Improved packaging

AI-assisted CRM logic

When Not To Use

Front-end UI work (use LWC/Aura)

Heavy ML computation

File processing

Desktop apps

Systems that need OS-level access

Final Summary

Apex is Salesforce's server-side programming language for enterprise automation.

Ideal for CRM logic, integrations, API building, and workflow automation.

Subject to governor limits requiring optimized coding patterns.

Core technology for scalable Salesforce development.

Faq

Is Apex only for Salesforce?

Yes - it runs exclusively on the Salesforce platform.

Does Apex support multithreading?

No - but async patterns exist.

Do I need Java to learn Apex?

No - but Java experience helps.

Can Apex be used for APIs?

Yes - REST & SOAP support built-in.

Code Sample Descriptions

1

Apex Counter and Theme Toggle

public class Counter {
    public Integer count = 0;
    public Boolean isDark = false;

    public void updateUI() {
        System.debug('Counter: ' + count);
        System.debug('Theme: ' + (isDark ? 'Dark' : 'Light'));
    }

    public void increment() { count++; updateUI(); }
    public void decrement() { count--; updateUI(); }
    public void reset() { count = 0; updateUI(); }
    public void toggleTheme() { isDark = !isDark; updateUI(); }
}

// Simulate actions
Counter c = new Counter();
c.updateUI();
c.increment();
c.increment();
c.toggleTheme();
c.decrement();
c.reset();

Demonstrates a simple counter with theme toggling using Apex classes and console output (system debug).

Let’s Try →
2

Apex Simple Addition

public class AddProgram {
    public Integer a = 5;
    public Integer b = 3;
    public Integer sum;

    public void calculate() {
        sum = a + b;
        System.debug('Sum: ' + sum);
    }
}

AddProgram ap = new AddProgram();
ap.calculate();

Adds two numbers and prints the result using System.debug.

Let’s Try →
3

Apex Factorial

public class FactorialProgram {
    public Integer n = 5;
    public Integer fact = 1;

    public void calculate() {
        for(Integer i = 1; i <= n; i++) {
        fact *= i;
        }
        System.debug('Factorial: ' + fact);
    }
}

FactorialProgram fp = new FactorialProgram();
fp.calculate();

Calculates factorial of a number using a loop.

Let’s Try →
4

Apex Fibonacci Sequence

public class FibonacciProgram {
    public void generate() {
        List<Integer> fib = new List<Integer>{0,1};
        for(Integer i=2;i<10;i++) {
        fib.add(fib[i-1]+fib[i-2]);
        }
        System.debug('Fibonacci: ' + fib);
    }
}

FibonacciProgram fp = new FibonacciProgram();
fp.generate();

Generates first 10 Fibonacci numbers using Apex lists.

Let’s Try →
5

Apex Max of Two Numbers

public class MaxProgram {
    public Integer a = 7;
    public Integer b = 10;

    public void findMax() {
        Integer max = (a > b) ? a : b;
        System.debug('Max: ' + max);
    }
}

MaxProgram mp = new MaxProgram();
mp.findMax();

Finds the maximum of two numbers.

Let’s Try →
6

Apex Array Sum

public class ArraySum {
    public void sumArray() {
        List<Integer> nums = new List<Integer>{1,2,3,4,5};
        Integer sum = 0;
        for(Integer n : nums) { sum += n; }
        System.debug('Sum: ' + sum);
    }
}

ArraySum as = new ArraySum();
as.sumArray();

Sums elements of an integer list.

Let’s Try →
7

Apex Even Numbers Filter

public class EvenNumbers {
    public void filter() {
        List<Integer> nums = new List<Integer>{1,2,3,4,5,6,7,8,9,10};
        for(Integer n : nums) {
        if(n % 2 == 0) System.debug(n);
        }
    }
}

EvenNumbers en = new EvenNumbers();
en.filter();

Displays even numbers from a list.

Let’s Try →
8

Apex String Concatenation

public class ConcatStrings {
    public void concat() {
        String str1 = 'HELLO';
        String str2 = 'WORLD';
        String result = str1 + str2;
        System.debug('Concatenated: ' + result);
    }
}

ConcatStrings cs = new ConcatStrings();
cs.concat();

Concatenates two strings and prints the result.

Let’s Try →
9

Apex Counter With Loop Simulation

public class LoopCounter {
    public void run() {
        Integer count = 1;
        while(count <= 5) {
        System.debug('Counter: ' + count);
        count++;
        }
    }
}

LoopCounter lc = new LoopCounter();
lc.run();

Counts from 1 to 5 using a loop with debug output.

Let’s Try →
10

Apex Conditional Increment

public class ConditionalIncrement {
    public void run() {
        Integer count = 3;
        if(count < 5) count++;
        System.debug('Counter: ' + count);
    }
}

ConditionalIncrement ci = new ConditionalIncrement();
ci.run();

Increment counter only if below 5.

Let’s Try →

Frequently Asked Questions about Apex

What is Apex?

Apex is a strongly typed, object-oriented programming language developed by Salesforce for building scalable, secure, and automated applications on the Salesforce platform. It allows developers to execute business logic on the server side, integrate external systems, and customize CRM workflows using a syntax similar to Java.

What are the primary use cases for Apex?

Salesforce triggers & automation. Custom REST & SOAP APIs. Batch & scheduled jobs. Complex CRM business logic. Integrations with external systems. Custom Salesforce Apps & packages

What are the strengths of Apex?

Native integration with Salesforce objects. Secure, scalable execution. Excellent tooling and test framework. Great for enterprise automation. Powerful asynchronous capabilities

What are the limitations of Apex?

Vendor lock-in to Salesforce ecosystem. Strict governor limits. Cannot interact with system file I/O. Restricted multithreading. Must follow Salesforce deployment rules

How can I practice Apex typing speed?

CodeSpeedTest offers 10+ real Apex code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.