Apex Data Types and Variables: A Beginner's Guide

Introduction

Welcome to Lesson 2 in our Salesforce Apex series! In this lesson, we will cover Apex data types and variables—the basic building blocks of Apex programming.

A variable is a placeholder used to store and manipulate data. Every variable in Apex has a data type, which defines what kind of values it can hold.

By the end of this guide, you’ll be able to: ✅ Understand different Apex data types
✅ Declare and use variables
✅ Manipulate strings and dates
✅ Complete a hands-on coding assignment


1️⃣ Data Types in Apex

Apex supports different kinds of data types, which are categorized as primitive types and complex types.

🔹 Primitive Data Types (Basic types)

These are the simplest types of data in Apex.

Data TypeDescriptionExample
IntegerWhole numbersInteger num = 10;
DoubleDecimal numbersDouble price = 99.99;
BooleanTrue/False valuesBoolean isActive = true;
StringText valuesString name = 'Rakesh';
DateStores only a dateDate today = Date.today();
TimeStores only timeTime now = Time.now();
DatetimeStores both date & timeDatetime current = Datetime.now();
LongLarge whole numbersLong bigNum = 123456789L;
IDSalesforce record IDId userId = UserInfo.getUserId();

🔹 Complex Data Types

These allow for storing multiple values.

Data TypeDescriptionExample
List<T>Ordered collectionList<String> names = new List<String>();
Set<T>Unique values onlySet<Integer> uniqueNums = new Set<Integer>();
Map<K, V>Key-value pairsMap<String, Integer> scoreMap = new Map<String, Integer>();
SObjectSalesforce ObjectAccount acc = new Account();

2️⃣ Declaring Variables

To create a variable in Apex, use this format:

dataType variableName = value;

Example:

Integer age = 25;
String fullName = 'Rakesh Neelam';
Boolean isAdmin = false;

3️⃣ Constants (Final Variables)

A constant is a variable that cannot be changed after being set.

final Integer MAX_USERS = 100;

❌ Trying to reassign MAX_USERS = 200; will cause an error.


4️⃣ Working with Strings

Apex provides several string methods to manipulate text.

String greeting = 'Hello, Salesforce!';
System.debug(greeting.toUpperCase()); // "HELLO, SALESFORCE!"
System.debug(greeting.length()); // 18
System.debug(greeting.substring(0, 5)); // "Hello"

5️⃣ Working with Dates and Datetime

Apex has built-in methods for date and time manipulation.

Date today = Date.today();
System.debug(today); // Prints today's date

Datetime currentTime = Datetime.now();
System.debug(currentTime); // Prints current date and time

🔹 Assignment 2: Practice with Variables

Your Task:

  1. Create an Apex class named DataTypeExample.

  2. Inside the class, declare:

    • An Integer variable with your age.

    • A String variable with your full name.

    • A Boolean variable to check if today is a weekend.

    • A Date variable with today’s date.

    • A Datetime variable with the current timestamp.

  3. Print all variables using System.debug().

  4. Execute the class using Anonymous Apex.

Example Solution (Try Writing it Yourself First!):

public class DataTypeExample {
    public static void showVariables() {
        Integer age = 28;
        String fullName = 'John Doe';
        Boolean isWeekend = (Date.today().dayOfWeek() == 6 || Date.today().dayOfWeek() == 7);
        Date today = Date.today();
        Datetime currentTime = Datetime.now();

        System.debug('Age: ' + age);
        System.debug('Full Name: ' + fullName);
        System.debug('Is it Weekend?: ' + isWeekend);
        System.debug('Today's Date: ' + today);
        System.debug('Current Time: ' + currentTime);
    }
}

To execute:

DataTypeExample.showVariables();

Next: Collections in Apex (Lists, Sets, Maps)