Apex Programming: Syntax, Data Types and Variables

May 12, 2025
864 Views
Apex Programming: Syntax, Data Types and Variables

On Day 2, we explored how to set up the Salesforce environment for Apex. Now, on Day 3, we’ll talk about Apex syntax, data types, and variables.

Introduction to Apex Syntax

Apex is a strongly typed, object oriented programming language that allows us to execute flow for business processes and enhance processes on Salesforce servers in conjunction with calls to the API. While its syntax is affected by languages like Java, Apex has its own set of rules that are optimized for Salesforce’s environment.

Also Read

Basic Syntax Rules

Apex code is written in classes and triggers if we compare a bit to other languages it’s similar. Every statement in Apex must end with a semicolon, Apex supports comments single-line comments starting with // and multi-line comments enclosed in /* */ . In detail related to Classes we will learn in other articles in this series for this one we have just given basic ideas.

As an example, please check on below snippet:


public class HelloWorld {
    public static void methodHello() {
        // Here it is a single-line comment
        System.debug('Hello, World!');
        /* Start of Multi Line comment
         
        End of Multi Line comment*/
    }
}

In the above snippet:

  • Class Declaration: The class is declared with the public access modifier.
  • Method Definition: The method methodHello is declared as static so that it can be invoked without creating an instance of the class which is inside the class.
  • System Debug: The System.debug statement is useful for logging output in the debug logs to debug our code, when we are trying to understand how code executes it will log for debug on a specific line of code in our class.

Apex syntax helps beginners to get started easily and quickly which is very basic before going through complex structures, while apex structure ensures that more complex applications remain organized and maintainable for scalability.

Introduction to Data Types and Collections

Apex provides several primitive data types and a set of collection types that are useful for writing code easily.

Primitive Data Types

The primitive data types in Apex includes:

  • Integer: Represents whole numbers.
  • Double: For floating point numbers.
  • Boolean: Represents true or false values.
  • String: For sequence of characters.
  • Date, Time and DateTime: Types to handle dates and times.
  • Id: A unique identifier for Salesforce records.

Below snippet is an example to declare and initialize these data types:


public class DataTypeExamples {
    public static void runExamples() {
        Integer myInt = 10;
        Double myDouble = 10.99;
        Boolean isActive = true;
        String greeting = 'Welcome to Apex!';
        Date today = Date.today();
        DateTime currentDateTime = DateTime.now();
        Id recordId = '001xx000003DGbYAAW';        
        System.debug('Integer: ' + myInt);
        System.debug('Double: ' + myDouble);
        System.debug('Boolean: ' + isActive);
        System.debug('String: ' + greeting);
        System.debug('Today\'s Date: ' + today);
        System.debug('Current DateTime: ' + currentDateTime);
        System.debug('Record Id: ' + recordId);
    }
}

In this example, we can see that it is simple to declare and initialize different data types. The use of System.debug allows developers to quickly check the output of their variables during execution.

Collections: Lists, Sets and Maps

For complex structure of Apex it supports powerful collection types that let us store and manage a set or group of elements

Lists

A List in Apex is a collection of elements. Lists are similar to arrays in other languages, but they can grow as needed. Below code shows the list of fruits with string data type.


List<String> fruits = new List<String>();
fruits.add('Apple');
fruits.add('Banana');
fruits.add('Cherry');
System.debug('Fruit List: ' + fruits);

Set

Sets are collections that do not allow duplicate values. They are useful when we want to ensure that every element is unique. Below code shows the set of numbers with integer data type.


Set<Integer> numbers = new Set<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(3); // Duplicate, will not be added
System.debug('Unique Numbers: ' + numbers);

Maps

Maps are key-value pairs. They allow us to store and retrieve values by using a unique key. Below code shows the map of fruitCalories with string as key and integer as values.

Map<String, Integer> fruitCalories = new Map<String, Integer>();
fruitCalories.put('Apple', 95);
fruitCalories.put('Banana', 105);
fruitCalories.put('Cherry', 50);
System.debug('Fruit Calories Map: ' + fruitCalories);

These collections make handling data much easier. Let’s say, we might use a list to iterate through records, a set to ensure unique IDs, or a map to quickly retrieve information based on a key with values if required.

Introduction to Variable Declaration and Initialization

Variables in Apex must be declared with a data type, which ensures the type of variable within the code. Let’s look at few of below examples:

Simple Variable Declaration

// Declare and initialize a variable in one line
String welcomeMessage = 'Hello, Salesforce!';
System.debug(welcomeMessage);

Delayed Initialization

Sometimes we want to declare a variable first and assign a value later:

Integer count;
count = 100;
System.debug('Count: ' + count);

This method of delayed initialization can be useful for us in scenarios where the value of the variable is computed or fetched from a database query when it’s required in the code.

Variables in Collections

When working with collections, we often declare variables to hold our lists, sets, maps and then populate them when it’s needed.


List<Integer> scores = new List<Integer>{85, 90, 95};
System.debug('Initial Scores: ' + scores);

This inline initialization of a list using curly braces is a shortcut that will be particularly useful for us when the values are known at the time of declaration.

Practical Examples and Real-World Scenario

All these concepts together with the help of a real example will help to understand it quickly. Let’s go through a small example that will represent a common scenario in a Salesforce org: Managing a list of student scores and checking if they passed based on a threshold.


public class StudentScores {
    public static void checkPassingScores() {
        // Declare and initialize a list of student scores
        List<Integer> scores = new List<Integer>{72, 85, 67, 90, 55};
        // Initialize a set to store passing scores (no duplicates)
        Set<Integer> passingScores = new Set<Integer>();
        Integer passingThreshold = 70;
        
        // Loop through the scores list
        for (Integer score : scores) {
            if (score >= passingThreshold) {
                passingScores.add(score);
            }
        }
        
        System.debug('Passing Scores: ' + passingScores);
    }
}

Below Screenshot Shows Actual Output for above code in debug log:

Actual Output for above code in debug log

In this example:

  • We start by creating a list of scores values.
  • We define a passing threshold and then use a loop to iterate through the scores.
  • If a score meets or exceeds the threshold, it will be added to a set, making sure that duplicate scores will not be recorded.
  • Finally, the result is logged using System.debug as an output shown in above snapshot.

This example demonstrates variable declaration, initialization and control structures in Apex and also shows the practical usage of collections to solve daily problems that we might face in activities.

Best Practices for Apex

As we work with Apex, below are few best practices to note it down and make sure to always follow:

  1. Use Proper Naming Conventions: Use clear and descriptive names for variables and methods.
  2. Add Comments for Complex Logic of Code: While our code should be self-explanatory, by adding comments it will help provide context and make it easier for others (or ourselves) to understand logic in future use and debugging.
  3. Use Collections Wisely: Collections are powerful and for Bulkification, but it’s important to choose the right type as per the use case.

Handle Exceptions: Always consider adding exception handling where appropriate.

Conclusion

Apex is a language with a complex or rich set of features and understanding its basics can help us in the way for more advanced development in Salesforce. We found that working through examples and experimenting with code was the best way to learn with our own org. Always exploring new stuff and we might make mistakes will always help us to learn new things quickly; that’s where real learning happens.

On Day 3, we explored the fundamental building blocks of Apex – its syntax, data types, and how to declare and use variables. These concepts form the core of every Apex program and are essential for writing clear and efficient code.

Up next, on Day 4, we’ll dive into Control Structures and Loops in Apex.

Stay tuned and follow the Apex 10-Day Series. Happy coding!

Written by

user

Mohit Bansal

Salesforce Technical Architect | Lead | Salesforce Lightning & Integrations Expert | Pardot | 5X Salesforce Certified | App Publisher | Blogger

Contributor of the month
contributor
Gopinath G

Passionate about the intersection of cutting-edge technologies

Get the latest tips, news, updates, advice, inspiration, and more….

...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...