Salesforce Apex Data Types – With Examples

data type is like a specialized container or box that can only hold specific kinds of values. Just as you wouldn’t put a basketball in a shoebox, different types of data need different types of containers.

Apex Data Types – Complete Visual Guide

🚀 Complete Apex Data Types Guide

Master Salesforce Apex Data Types with Interactive Visualizations

15+
Data Types
50+
Examples
25+
Interactive Demos
100%
Hands-on

What is a Data Type?

Understanding data types through visual containers and interactive examples

🎯 Data Types as Containers
Think of Data Types as Different Sized Boxes

A data type is like a specialized container or box that can only hold specific kinds of values. Just as you wouldn’t put a basketball in a shoebox, different types of data need different types of containers.

Integer Box
42
Size: 4 bytes
Range: ±2 billion
String Box
“Hello”
Size: Variable
Content: Text
Boolean
true
Size: 1 byte
Values: true/false
Decimal Box
199.99
Size: Variable
Precision: Exact

🎮 Try dropping these values into the right containers:

100
“Apex”
false
29.99
“text” → Integer?

💾 Memory Layout Visualization

4 bytes
Integer
Variable
String
1 byte
Boolean
Variable
Decimal

Each data type uses different amounts of memory – like different sized storage containers

🌍 Real-World Analogies
📦

Shipping Boxes

Small items go in small boxes, large items need big boxes. You can’t fit a refrigerator in an envelope!

Like: Boolean = small box, String = expandable box
🏠

Room Types

Kitchen is for cooking, bedroom for sleeping, bathroom for hygiene. Each room has a specific purpose!

Like: Integer for numbers, String for text, Boolean for yes/no
🧰

Tool Box

Screwdriver for screws, hammer for nails, wrench for bolts. Right tool for the right job!

Like: Decimal for money, Date for time, ID for records
🚀 Ready to Explore?
Now that you understand what data types are, let’s dive deep into each type!

Primitive Data Types

Fundamental building blocks of Apex programming with detailed specifications and interactive examples

🔢
Integer
32-bit Signed Integer
A 32-bit signed integer that can hold whole numbers from -2,147,483,648 to 2,147,483,647. Most commonly used for counting, indexing, and simple arithmetic operations.
Size
32 bits
Memory
4 bytes
Min Value
-2³¹
Max Value
2³¹-1
// Integer declarations and operations Integer count = 100; Integer negative = -50; Integer maxInt = 2147483647; // Arithmetic operations Integer sum = count + 25; // 125 Integer product = count * 3; // 300 Integer remainder = count % 7; // 2
🧮 Integer Calculator & Validator
Enter a number to analyze…
Memory Usage
4 bytes per integer
Performance Tips
  • Most efficient for simple counting and indexing
  • Use for loop counters and array indices
  • Avoid overflow – check bounds for calculations
  • Prefer Integer over Long when range suffices
📏
Long
64-bit Signed Integer
A 64-bit signed integer for handling very large whole numbers, timestamps, and calculations that exceed Integer range. Essential for working with System.currentTimeMillis() and large datasets.
Size
64 bits
Memory
8 bytes
Min Value
-2⁶³
Max Value
2⁶³-1
// Long declarations Long timestamp = System.currentTimeMillis(); Long bigNumber = 9223372036854775807L; Long calculation = 1000000L * 1000000L; // Common use cases Long startTime = System.currentTimeMillis(); // … some processing … Long duration = System.currentTimeMillis() – startTime;
⏱️ Long Number & Timestamp Tool
Enter a number or get current timestamp…
Memory Usage
8 bytes per long
Performance Tips
  • Essential for timestamp operations
  • Use for large mathematical calculations
  • Required when Integer range is insufficient
  • Add ‘L’ suffix for long literals
📝
String
Unicode Character Sequence
Immutable sequence of Unicode characters. Strings are objects in Apex and provide extensive methods for manipulation. Maximum length is approximately 6,000,000 characters.
Encoding
UTF-16
Per Char
2 bytes
Max Length
~6M chars
Mutability
Immutable
// String declarations and literals String name = ‘John Doe’; String message = “Hello World”; String multiline = ‘Line 1\nLine 2\nLine 3’; // String operations String fullName = firstName + ‘ ‘ + lastName; String upper = name.toUpperCase(); Integer length = name.length(); Boolean contains = message.contains(‘World’);
🔤 String Analyzer & Manipulator
Enter text to analyze…
Memory Usage
Variable (2 bytes × length)
Performance Tips
  • Strings are immutable – concatenation creates new objects
  • Use StringBuilder pattern for multiple concatenations
  • String.format() is more readable than concatenation
  • Consider String.join() for array/list joining
Boolean
True/False Values
Represents logical values: true or false. Essential for conditional logic, flags, and control flow. Despite being conceptually 1 bit, it’s stored as 1 byte in memory for addressing efficiency.
Values
true/false
Memory
1 byte
Logical Size
1 bit
Default
false
// Boolean declarations Boolean isActive = true; Boolean hasAccess = false; Boolean result = (5 > 3); // true // Logical operations Boolean combined = isActive && hasAccess; // false Boolean either = isActive || hasAccess; // true Boolean negation = !isActive; // false
🔀 Boolean Logic Simulator
Select values and operation…
Memory Usage
1 byte (8 bits) per boolean
Performance Tips
  • Most memory-efficient primitive type
  • Use for flags and conditional states
  • Boolean expressions are short-circuited
  • Default value is false for instance variables
💰
Decimal
Arbitrary Precision Decimal
High-precision decimal number ideal for financial calculations. Maintains exact decimal precision without floating-point rounding errors. Supports up to 28-29 significant digits with configurable scale.
Precision
28-29 digits
Scale
Configurable
Memory
Variable
Rounding
Exact
// Decimal declarations Decimal price = 199.99; Decimal taxRate = 0.0825; Decimal precise = 123.456789012345678901234567890; // Financial calculations Decimal tax = price * taxRate; Decimal total = price + tax; Decimal rounded = total.setScale(2);
💸 Financial Calculator
Enter a price to calculate tax and totals…
Memory Usage
Variable (based on precision)
Performance Tips
  • Always use Decimal for currency and financial data
  • More memory intensive than Double but exact
  • Use setScale() for consistent decimal places
  • Supports arbitrary precision arithmetic
🔬
Double
64-bit Floating Point
IEEE 754 double-precision floating-point number. Suitable for scientific calculations where approximate values are acceptable. Provides ~15-17 decimal digits of precision.
Size
64 bits
Precision
15-17 digits
Range
±1.7E±308
Standard
IEEE 754
// Double declarations Double pi = 3.14159265359; Double scientific = 1.23E-4; // 0.000123 Double calculation = Math.sqrt(2.0); // Scientific operations Double area = pi * Math.pow(radius, 2); Double result = Math.sin(pi / 2); // 1.0
🧪 Scientific Calculator
Enter a number for scientific calculations…
Memory Usage
8 bytes (64 bits)
Performance Tips
  • Use for scientific and engineering calculations
  • Avoid for financial calculations (use Decimal)
  • Be aware of floating-point precision limits
  • More efficient than Decimal for math operations
📅
Date
Calendar Date Only
Represents a calendar date without time information. Includes year, month, and day. Useful for birthdays, due dates, and any date-only scenarios.
Components
Year/Month/Day
Memory
8 bytes
Range
1700-4000
Format
YYYY-MM-DD
// Date creation methods Date today = Date.today(); Date birthday = Date.newInstance(1990, 5, 15); Date parsed = Date.valueOf(‘2024-12-25’); // Date operations Date tomorrow = today.addDays(1); Integer daysBetween = today.daysBetween(birthday); String formatted = today.format();
📆 Date Calculator
Select dates to perform calculations…
Memory Usage
8 bytes per date
Performance Tips
  • Use Date for date-only scenarios (birthdays, due dates)
  • More efficient than DateTime when time isn’t needed
  • Supports date arithmetic (addDays, addMonths, etc.)
  • Always use Date.today() for current date
DateTime
Date + Time + Timezone
Complete timestamp including date, time, and timezone information. Essential for logging, scheduling, and any time-sensitive operations. Always stored in GMT and converted for display.
Components
Date+Time+TZ
Memory
16 bytes
Precision
Milliseconds
Storage
GMT/UTC
// DateTime creation DateTime now = DateTime.now(); DateTime specific = DateTime.newInstance(2024, 12, 25, 14, 30, 0); DateTime parsed = DateTime.valueOf(‘2024-12-25 14:30:00’); // DateTime operations DateTime later = now.addHours(5); String formatted = now.format(‘yyyy-MM-dd HH:mm:ss’); Long timestamp = now.getTime();
🕐 DateTime Operations
Click buttons to explore DateTime operations…
Memory Usage
16 bytes per datetime
Performance Tips
  • Use for timestamps, logging, and scheduling
  • Always stored in GMT – timezone conversion for display
  • More expensive than Date when time isn’t needed
  • Use DateTime.now() for current timestamp
🆔
ID
Salesforce Record Identifier
Unique 15 or 18 character identifier for Salesforce records. The 15-character version is case-sensitive, while the 18-character version includes a checksum for case-insensitive operations.
Length
15 or 18 chars
Format
Base62
Uniqueness
Global
Case
Sensitive
// ID declarations and usage ID accountId = ‘001D000001234567’; // 15-char ID contactId = ‘003D000001234567ABC’; // 18-char ID recordId = someRecord.Id; // ID operations String idString = String.valueOf(accountId); Schema.SObjectType objType = accountId.getSObjectType(); Boolean isValid = (accountId != null);
🔍 ID Validator & Analyzer
Enter a Salesforce ID to validate and analyze…
Memory Usage
15-18 bytes per ID
Performance Tips
  • Use for record references and SOQL queries
  • 18-char format is safer for external systems
  • Always check for null before using
  • Can be used to determine object type from prefix
📄
Blob
Binary Large Object
Binary data container for files, images, documents, and other binary content. Commonly used with attachments, encoding/decoding operations, and HTTP requests.
Content
Binary Data
Max Size
6MB (heap)
Encoding
Base64
Use Cases
Files/Images
// Blob creation and usage Blob textBlob = Blob.valueOf(‘Hello World’); Blob base64Blob = EncodingUtil.base64Decode(‘SGVsbG8gV29ybGQ=’); Blob pdfBlob = [SELECT Body FROM Attachment WHERE Id = :attachId].Body; // Blob operations String encoded = EncodingUtil.base64Encode(textBlob); Integer size = textBlob.size(); String text = textBlob.toString();
📁 Blob Encoder/Decoder
Enter text or Base64 to work with Blobs…
Memory Usage
Variable (1 byte per byte + overhead)
Performance Tips
  • Use for binary data (files, images, documents)
  • Be mindful of heap size limits (6MB)
  • Base64 encoding increases size by ~33%
  • Consider streaming for large files

sObject Data Types

Salesforce Objects representing records in the database with comprehensive field structures

📊 Standard Account Object Structure
Id
ID
Unique 18-char identifier
Name
String(255)
Required field
Type
Picklist
Customer, Partner, etc.
Industry
Picklist
Technology, Healthcare, etc.
AnnualRevenue
Currency
Company’s annual revenue
NumberOfEmployees
Integer
Employee count
Phone
Phone
Main phone number
Website
URL
Company website
BillingAddress
Address
Compound field
CreatedDate
DateTime
Auto-populated
CreatedById
Reference(User)
Lookup to User
LastModifiedDate
DateTime
Auto-updated
OwnerId
Reference
User or Queue
Custom_Field__c
Text(Custom)
Organization-specific

📝 sObject Declaration & Usage

// Standard sObject types Account acc = new Account(); Contact con = new Contact(); Opportunity opp = new Opportunity(); // Custom sObject (example) Custom_Object__c customRecord = new Custom_Object__c(); // Generic sObject sObject genericRecord = new Account(); String objectType = genericRecord.getSObjectType().getDescribe().getName();
🏗️ sObject Creator
Select an sObject type to create an instance…

🔧 Field Access Methods

// Direct field access Account acc = new Account(); acc.Name = ‘Acme Corporation’; acc.Type = ‘Customer’; String accountName = acc.Name; // Dynamic field access String fieldName = ‘Industry’; acc.put(fieldName, ‘Technology’); Object fieldValue = acc.get(fieldName); String industry = (String) fieldValue; // Field existence check Boolean hasField = acc.isSet(‘AnnualRevenue’);
🎯 Field Manipulator
Configure field operations above…

🔗 Relationship Navigation

// Parent-to-child relationships (subqueries) Account acc = [SELECT Name, (SELECT Name, Email FROM Contacts) FROM Account LIMIT 1]; // Child-to-parent relationships Contact con = [SELECT Name, Account.Name, Account.Type FROM Contact LIMIT 1]; // Accessing related data String contactName = con.Name; String accountName = con.Account.Name; List<Contact> relatedContacts = acc.Contacts;
🌐 Relationship Explorer
Select a relationship type to explore…

📋 sObject Metadata & Inspection

// sObject type inspection Schema.SObjectType accountType = Account.sObjectType; Schema.DescribeSObjectResult describe = accountType.getDescribe(); String label = describe.getLabel(); String apiName = describe.getName(); // Field inspection Map<String, Schema.SObjectField> fieldMap = describe.fields.getMap(); Schema.SObjectField nameField = fieldMap.get(‘Name’); Schema.DescribeFieldResult fieldDesc = nameField.getDescribe(); // Record type information List<Schema.RecordTypeInfo> recordTypes = describe.getRecordTypeInfos();
🔍 sObject Inspector
Select an object to inspect its metadata…

Collection Data Types

Powerful data structures for handling multiple values with different behaviors and use cases

📋 List<T> – Ordered Collection

0 “Apple”
1 “Banana”
2 “Cherry”
3 “Apple”
✓ Ordered
✓ Indexed Access
✓ Allows Duplicates
✓ Dynamic Size
// List creation and manipulation List<String> fruits = new List<String>{‘Apple’, ‘Banana’, ‘Cherry’}; fruits.add(‘Date’); // Adds at end fruits.add(1, ‘Avocado’); // Insert at index 1 // Access and modification String first = fruits[0]; // “Apple” fruits[0] = ‘Apricot’; // Replace first element Integer size = fruits.size(); // Current size Boolean contains = fruits.contains(‘Banana’); // true // Iteration for (String fruit : fruits) { System.debug(fruit); }
📝 List Operations Playground
Add items to see list operations…

🎯 Set<T> – Unique Values Collection

“Apple”
“Banana”
“Cherry”
✗ Unordered
✗ No Index Access
✗ No Duplicates
✓ Fast Lookup
// Set creation and manipulation Set<String> uniqueFruits = new Set<String>{‘Apple’, ‘Banana’, ‘Apple’}; // Only contains: Apple, Banana (duplicate removed) uniqueFruits.add(‘Cherry’); // Adds new item uniqueFruits.add(‘Apple’); // No effect (already exists) // Set operations Boolean hasApple = uniqueFruits.contains(‘Apple’); // true Integer size = uniqueFruits.size(); // 3 uniqueFruits.remove(‘Banana’); // Removes item // Convert to List List<String> listFromSet = new List<String>(uniqueFruits);
🎯 Set Operations Playground
Add items to see set operations (duplicates will be ignored)…

🗺️ Map<K,V> – Key-Value Pairs

Key: “CA”
Value: “California”
Key: “TX”
Value: “Texas”
Key: “NY”
Value: “New York”
✓ Key-Value Pairs
✓ Unique Keys
✓ Fast Lookup
✗ Unordered
// Map creation and manipulation Map<String, String> stateMap = new Map<String, String>{ ‘CA’ => ‘California’, ‘TX’ => ‘Texas’, ‘NY’ => ‘New York’ }; // Map operations String stateName = stateMap.get(‘CA’); // “California” stateMap.put(‘FL’, ‘Florida’); // Add new pair Boolean hasKey = stateMap.containsKey(‘TX’); // true // Getting keys and values Set<String> keys = stateMap.keySet(); List<String> values = stateMap.values(); Integer size = stateMap.size();
🗺️ Map Operations Playground
Add key-value pairs to see map operations…
🚀 Advanced Collection Operations
🔄 Collection Conversion
List → Set Remove Duplicates
Set → List Enable Indexing
SOQL → Map Fast ID Lookup
// Collection conversions List<String> listWithDups = new List<String>{‘A’, ‘B’, ‘A’}; Set<String> uniqueSet = new Set<String>(listWithDups); List<String> uniqueList = new List<String>(uniqueSet); // SOQL to Map Map<Id, Account> accountMap = new Map<Id, Account>( [SELECT Id, Name FROM Account LIMIT 10] );
Click to see collection conversions…
📊 Performance Comparison
Operation List Set Map
Add Element O(1) O(1) O(1)
Search/Contains O(n) O(1) O(1)
Remove Element O(n) O(1) O(1)
Access by Index O(1) N/A N/A
Click to benchmark collection operations…

Comparison & Best Practices

Comprehensive comparison tables and expert recommendations for choosing the right data types

Data Type Memory Size Range/Capacity Primary Use Cases Performance Example
Integer 4 bytes -2³¹ to 2³¹-1 Counters, loop indices, quantities ⚡ Fastest Integer count = 100;
Long 8 bytes -2⁶³ to 2⁶³-1 Timestamps, large numbers ⚡ Very Fast Long timestamp = System.currentTimeMillis();
Double 8 bytes ±1.7E±308 (15-17 digits) Scientific calculations, math ⚡ Fast Double pi = Math.PI;
Decimal Variable 28-29 significant digits Currency, financial calculations 🐌 Slower but precise Decimal price = 199.99;
String 2 bytes/char ~6M characters Text, names, descriptions 🐌 Memory intensive String name = ‘John Doe’;
Boolean 1 byte true or false Flags, conditional logic ⚡ Fastest Boolean isActive = true;
ID 15-18 bytes Salesforce records only Record references, SOQL ⚡ Fast ID accountId = ‘001D000001234567’;
Date 8 bytes 1700-4000 (approx) Birthdays, due dates ⚡ Fast Date birthday = Date.newInstance(1990, 5, 15);
DateTime 16 bytes Date + Time + Timezone Timestamps, logging, scheduling ⚡ Fast DateTime now = DateTime.now();
Blob Variable 6MB (heap limit) Binary data, files, images 🐌 Memory intensive Blob data = Blob.valueOf(‘Hello’);
List<T> Variable Limited by heap Ordered data, indexed access ⚡ Fast access, 🐌 search List<String> items = new List<String>();
Set<T> Variable Limited by heap Unique values, fast lookup ⚡ Very fast lookup Set<String> unique = new Set<String>();
Map<K,V> Variable Limited by heap Key-value relationships ⚡ Very fast lookup Map<String, String> data = new Map<String, String>();
🎯 Decision Matrix: When to Use Each Type
💻 Numbers & Mathematics
Integer: Loop counters, quantities, simple math
Long: Timestamps, large calculations, System.currentTimeMillis()
Double: Scientific calculations, trigonometry, engineering
Decimal: Money, currency, precise financial calculations
Click to see number type examples…
📝 Text & Content
String: Names, descriptions, user input, messages
ID: Record references, SOQL WHERE clauses
Blob: Files, images, binary content, attachments
Click to see text type examples…
📅 Time & Dates
Date: Birthdays, due dates, anniversaries (no time needed)
DateTime: Logging, scheduling, created/modified timestamps
Long: Unix timestamps, duration calculations
Click to see date/time examples…
📦 Collections & Storage
List: Ordered data, need indexing, allow duplicates
Set: Unique values, fast membership testing, remove duplicates
Map: Key-value relationships, fast lookups, caching
Click to see collection examples…
🏆 Best Practices & Common Pitfalls
✅ Do’s
  • ✓ Use Decimal for all financial calculations
  • ✓ Always check for null before operations
  • ✓ Use Set for uniqueness requirements
  • ✓ Pre-size collections when size is known
  • ✓ Use String.join() for multiple concatenations
  • ✓ Choose smallest appropriate numeric type
  • ✓ Use Map for fast key-based lookups
❌ Don’ts
  • ✗ Don’t use Double for currency calculations
  • ✗ Don’t concatenate strings in loops
  • ✗ Don’t ignore potential overflow scenarios
  • ✗ Don’t use List.contains() for large datasets
  • ✗ Don’t assume collections are never null
  • ✗ Don’t use inappropriate types for size/performance
  • ✗ Don’t forget about heap size limits
🎓 Knowledge Check
Test your understanding of Apex data types

Must Read

Uday Bheemarpu
Uday Bheemarpu
Articles: 9

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *

Discover more from Panther Schools

Subscribe now to keep reading and get access to the full archive.

Continue reading