What are Apex Data Types in Salesforce?

Apex data types define the kind of value a variable, method parameter, return value, class field, or collection element can store in Salesforce Apex. A type can represent a simple value such as a number or text, a Salesforce record such as an Account, a collection such as a List, Set, or Map, an enum value, or an instance of an Apex class.

Salesforce Apex is a strongly typed, object-oriented programming language used on the Salesforce Platform. It is similar in style to C# and Java, but it is designed to work with Salesforce data, transactions, triggers, and platform services. In this Salesforce tutorial, we will learn the main categories of Apex data types: primitive data types, collections, sObjects, enums, and user-defined class types.

Apex Data Types List Used in Salesforce Code

Salesforce supports the following broad Apex data type categories:

  1. Primitive data types.
  2. Collections.
  3. sObjects.
  4. Enums.
  5. Classes, interfaces, and user-defined object types.

Because Apex is strongly typed, a variable must be declared with a type before it can be used. The compiler checks whether assigned values and method calls match the declared type.

</>
Copy
String customerName = 'Acme Corporation';
Integer numberOfEmployees = 50;
Boolean isActive = true;
Account acc = new Account(Name = customerName);

Primitive Data Types in Apex

Primitive data type includes Integer, Double, Long, Date, Date Time, String, ID and Boolean.

  • All primitive data types are passed by value, not by reference.
  • All Apex variables, whether they are class member variable, are initialized to null. Make sure that we initialize variables to appropriate values before using them.

The commonly used primitive types in Apex include Blob, Boolean, Date, Datetime, Decimal, Double, Id, Integer, Long, String, and Time. Primitive variables can hold null, so code should check for null values before using methods or performing calculations.

Apex primitive typeUse in Salesforce ApexExample value
BooleanStores true, false, or nulltrue
IntegerStores whole numbers within 32-bit integer range25
LongStores larger whole numbers9000000000L
DecimalStores precise decimal values, often used for currency or calculations requiring precision1250.75
DoubleStores decimal values using double precision floating-point representation12.5
StringStores text'Salesforce'
IdStores a Salesforce record identifier001...
DateStores year, month, and day without time2026-06-24
DatetimeStores date and time2026-06-24 10:30:00
TimeStores hour, minute, second, and millisecond without a date10:30:00.000
BlobStores binary dataFile or encoded data

Boolean Type for True, False, and Null Values

A value that can only be assigned True, False or Null.

Eg :- Boolean isActive=”False”.

In Apex, Boolean literals are written as true and false without quotation marks. If quotation marks are used, the value becomes text, not a Boolean value.

</>
Copy
Boolean isActive = false;

if (isActive == true) {
    System.debug('The record is active.');
} else {
    System.debug('The record is not active.');
}

Date Type for Calendar Dates in Apex

A value that indicates a particular day, date values contain no information about time. Date value must always be created with a system static method.

Eg:- Date myDate=Date.newinstance(2017,09,15).

output : 2017-09-15 00:00:00.

A Date value stores only the year, month, and day. It does not store hours, minutes, seconds, or milliseconds. Use Date.newInstance(year, month, day) to create a date value clearly.

</>
Copy
Date invoiceDate = Date.newInstance(2026, 6, 24);
Date dueDate = invoiceDate.addDays(30);
System.debug(dueDate);
2026-07-24 00:00:00

Time and Datetime Types for Time-Based Apex Logic

These are date types associated with dates and times along with date data type. The time data types stores times(Hours, minutes, seconds and milliseconds). The date data type stores dates(Years, month and day).

Use Time when the value should contain a time of day without a date. Use Datetime when the value must include both date and time, such as a scheduled action time, created timestamp, or integration timestamp.

</>
Copy
Time meetingTime = Time.newInstance(10, 30, 0, 0);
Datetime meetingDateTime = Datetime.newInstance(2026, 6, 24, 10, 30, 0);

System.debug(meetingTime);
System.debug(meetingDateTime);

Integer, Long, Double, and Decimal Numeric Types

To store numeric values in variables, declare variables with one of the numeric data types Integer, Long, Double and Decimal.

Use Integer for normal whole-number counters, Long for larger whole numbers, Decimal for precise values such as currency amounts, and Double for floating-point numeric values where precision rules are different from Decimal.

Integer Type for Whole Numbers in Apex

A 32-bit numbers that doesn’t include a decimal point. Integer have a minimum value of -2,147,483,648 and a maximum of 2,147,483,648.

Example : Integer i=1;

An Apex Integer is a 32-bit signed whole number. Its minimum value is -2,147,483,648 and its maximum value is 2,147,483,647. Use Long when a whole number may exceed this range.

</>
Copy
Integer quantity = 10;
Decimal unitPrice = 99.95;
Decimal totalAmount = quantity * unitPrice;

System.debug(totalAmount);
999.50

String and Id Types Used with Salesforce Records

A String stores text such as names, email addresses, descriptions, and status labels. Apex strings are written inside single quotation marks. The Id type stores Salesforce record IDs and helps the compiler treat the value as a record identifier instead of ordinary text.

</>
Copy
String accountName = 'Acme Corporation';
Id accountId = '001000000000000AAA';

System.debug(accountName);
System.debug(accountId);

Although Salesforce IDs can be stored as strings, using the Id type makes the code clearer when the value represents a Salesforce record.

Collections in Apex: List, Set, and Map

Apex collections store multiple values in one variable. Collections are strongly typed, so the element type must be declared. The three main collection types are List, Set, and Map.

Collection typeWhat it storesTypical use
List<T>Ordered values of the same typeLooping through queried records in order
Set<T>Unique values of the same typeCollecting unique IDs or names
Map<K,V>Key-value pairsFinding a record quickly by ID or another key
</>
Copy
List<String> stages = new List<String>{'Prospecting', 'Qualification', 'Closed Won'};
Set<Id> accountIds = new Set<Id>();
Map<Id, Account> accountMap = new Map<Id, Account>();

Collections are used frequently in triggers, batch Apex, service classes, and controller logic because Salesforce code often works with groups of records rather than only one record.

sObject Data Types for Salesforce Records

An sObject is a Salesforce object record in Apex. Standard objects such as Account, Contact, and Opportunity have strongly typed sObject classes. Custom objects use the API name ending in __c, such as Invoice__c.

</>
Copy
Account acc = new Account();
acc.Name = 'Acme Corporation';
acc.Phone = '9999999999';

insert acc;

You can also use the generic sObject type when code needs to handle different Salesforce object types. When you know the object type, a specific type such as Account is usually clearer and safer.

</>
Copy
sObject genericRecord = new Account(Name = 'Generic Account');
Account typedAccount = (Account) genericRecord;
System.debug(typedAccount.Name);

Enum Data Types for Fixed Apex Values

An enum is useful when a variable should accept only a fixed set of named values. This improves readability and avoids repeated text literals in conditions.

</>
Copy
public enum PriorityLevel {
    LOW,
    MEDIUM,
    HIGH
}

PriorityLevel casePriority = PriorityLevel.HIGH;

if (casePriority == PriorityLevel.HIGH) {
    System.debug('Handle this case first.');
}

Object, Class, and User-Defined Types in Apex

Object

Object is a instance of the class. This has both state and behaviour. Memory for the data members are allocated only when we create an object.

Syntax

</>
Copy
Classname Objectname = new Classname();
  • Classname – This is the name of the class for which we are creating an object.
  • Objectname – It’s a reference variable.
  • new – It is a keyword which we are allocating the memory.
  • Classname() – Constructor.

In Apex, the general Object type can hold different kinds of values, but it should be used carefully because the code may need casting before calling type-specific methods or fields. For most business logic, prefer a specific type such as Account, String, Integer, or a custom class name.

What is a Class?

A class is a collection of data members and methods.

</>
Copy
class Student {
	Integer no;
	String name;
	public void getDetails() {
		System.debug('rollno'+no);
		System.debug('name'+name);
	}
}

A class can be used as a data type. After a class is defined, variables can be declared using the class name, and objects can be created from it.

</>
Copy
Student s1 = new Student();
s1.no = 101;
s1.name = 'Ravi';
s1.getDetails();

How to define an Apex class ?

To define an Apex class, we must use Access modifiers for the top level class(public or global), optional modifiers such as virtual, abstract, the keywords class followed by class name and optional extensions like AND/OR.

</>
Copy
private/public/global[virtual/abstract/With Sharing/(none)]
class classname [implements InterfaceNameList / (none)][extends classname/(none)] {
	// body of this class
}

In practical Apex code, access modifiers and sharing keywords should be chosen based on how the class is used. For example, with sharing enforces the current user’s sharing rules, while without sharing does not enforce those sharing rules for the class.

Null Values and Type Safety in Apex Variables

Most Apex variables are initialized to null when no value is assigned. A common beginner error is calling a method or accessing a field on a null variable. Initialize variables before using them, and add null checks where a value may be missing.

</>
Copy
String customerName;

if (customerName != null) {
    System.debug(customerName.toUpperCase());
} else {
    System.debug('Customer name is not available.');
}

Type safety also prevents assigning an incompatible value to a variable. For example, a text value cannot be assigned directly to an Integer variable unless it is converted using an appropriate method.

</>
Copy
String quantityText = '25';
Integer quantity = Integer.valueOf(quantityText);
System.debug(quantity);

Apex Data Type Selection Examples

The correct Apex data type depends on what the value represents and how it will be used. The following examples show common choices in Salesforce development.

RequirementRecommended Apex typeReason
Store the name of an AccountStringIt is text.
Store whether a Contact is activeBooleanIt is a true or false condition.
Store a Salesforce record IDIdIt represents a record identifier.
Store an Account recordAccountIt is a specific Salesforce sObject.
Store many Contact recordsList<Contact>It stores multiple ordered records.
Store unique Account IDsSet<Id>It avoids duplicate IDs.
Find Account records by IDMap<Id, Account>It supports fast lookup by key.
Store a fixed status listenumIt restricts values to named constants.

Common Mistakes with Salesforce Apex Data Types

  • Using quoted Boolean values: write false, not 'false' or "False".
  • Confusing Date and Datetime: use Date for a calendar date and Datetime when time is also required.
  • Using String for Salesforce IDs everywhere: prefer Id when the value represents a record identifier.
  • Forgetting null checks: variables can be null, and calling methods on null values causes runtime errors.
  • Choosing List when uniqueness is required: use Set for unique values such as unique record IDs.
  • Using generic Object unnecessarily: choose a specific type when the expected data type is known.

FAQs on Salesforce Apex Data Types

What are the main Apex data types in Salesforce?

The main Apex data type categories are primitive types, collections, sObjects, enums, and user-defined class types. Primitive types store simple values, collections store multiple values, sObjects represent Salesforce records, enums define fixed named values, and classes define custom object types.

Is String a primitive data type in Apex?

Yes. String is treated as a primitive data type in Apex and is used to store text values such as names, email addresses, labels, and descriptions.

What is the difference between Date and Datetime in Apex?

Date stores only year, month, and day. Datetime stores both date and time. Use Date for values such as invoice date or birth date, and use Datetime for values such as scheduled execution time or created timestamp.

When should I use List, Set, and Map in Apex?

Use List when order matters or duplicates are allowed. Use Set when values must be unique. Use Map when each value should be found by a key, such as finding an Account by its ID.

Can an Apex variable have a null value?

Yes. Apex variables can be null when no value has been assigned. Code should check for null before calling methods or accessing fields on variables that may not have a value.

Editorial QA Checklist for Apex Data Types Tutorial

  • Confirm that Apex primitive type names are written with correct capitalization, such as Boolean, Date, Datetime, Decimal, Id, and String.
  • Check that Boolean examples use true or false without quotation marks.
  • Verify that Integer range examples use -2,147,483,648 to 2,147,483,647.
  • Ensure that collection examples declare element types, such as List<String>, Set<Id>, and Map<Id, Account>.
  • Confirm that sObject examples use valid Salesforce object names such as Account and Contact.
  • Review code blocks to make sure new syntax examples use PrismJS-compatible language classes.