Long
Learning Content
Last updated: July 28, 2026
Long Data Type
The Long data type is used to store very large whole numbers without decimal places. It works similarly to the Integer data type but supports a much larger numeric range, making it suitable for applications that process massive datasets or extremely large values.
Although most Salesforce business applications use Integer for counting and numbering, Long becomes essential when working with billions of records, large financial statistics, data migrations, analytics, or integrations that return very large numeric values.
💡 LearnFrenzy Insight
Imagine counting the number of stars in a galaxy or the total website visits over many years. A normal calculator can easily count hundreds or thousands, but eventually the numbers become extremely large.
Similarly, Integer has a maximum limit. When your value exceeds that limit, you should use the Long data type.
What is a Long?
A Long stores signed whole numbers that are much larger than those supported by the Integer data type. It does not support decimal values. Long is a 64-bit signed two's complement integer, which means it can represent values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
Long totalVisitors = 9876543210L; Long fileSize = 5368709120L; Long population = 8123456789L; Long negativeValue = -5000000000L; // Negative Long values are also supported Long zeroValue = 0L; // Zero is also valid
Notice the L suffix used with large numeric literals. It tells Apex to treat the value as a Long.
💡 Pro Tip: The L suffix is case-insensitive (you can use l or L), but using uppercase L is recommended for better readability.
Long Range & Characteristics
A Long occupies 64 bits (8 bytes) of memory and supports a significantly larger range than Integer.
| Property | Value |
|---|---|
| Minimum Value | -9,223,372,036,854,775,808 |
| Maximum Value | 9,223,372,036,854,775,807 |
| Memory Size | 64-bit (8 Bytes) |
| Default Value | null (when declared but not initialized) |
| Integer Equivalent Range | ~2.1 billion (much smaller) |
⚠️ Important Note on Range: The Long range is approximately 9.2 quintillion (9.2 × 10^18). This is sufficient for almost all business applications, including counting records across multiple large Salesforce orgs.
Variable Declaration & Initialization
You can declare and initialize Long variables in several ways:
// Method 1: Declaration with initialization (with L suffix)
Long totalRecords = 5000000000L;
Long totalDownloads = 12500000000L;
// Method 2: Declaration without initialization (defaults to null)
Long storageUsed;
storageUsed = 8796093022208L; // Initialization later
// Method 3: Without L suffix (within Integer range)
Long smallValue = 1000; // No L needed for small values
// Method 4: From Integer
Integer count = 1000;
Long longFromInt = Long.valueOf(count); // 1000
// Method 5: From String
Long parsed = Long.valueOf("9876543210");
// Method 6: Using scientific notation (not common for Long)
Long largeValue = 5_000_000_000L; // Underscores for readability (Java-style)
📝 Key Points:
- Uninitialized Long variables default to
null, not 0. - Always use the
Lsuffix when the value exceeds the Integer range. - Values within the Integer range (-2,147,483,648 to 2,147,483,647) don't require the
Lsuffix. - Use descriptive names like
totalApiRequestsorstorageUsed.
Basic Arithmetic Operations
Longs support all standard arithmetic operations just like Integers:
Long totalUsers = 8000000000L;
Long newUsers = 250000000L;
// Basic Arithmetic
System.debug('Addition: ' + (totalUsers + newUsers)); // 8250000000
System.debug('Subtraction: ' + (totalUsers - newUsers)); // 7750000000
System.debug('Multiplication: ' + (totalUsers * 2)); // 16000000000
System.debug('Division: ' + (totalUsers / 2)); // 4000000000
System.debug('Modulus: ' + (totalUsers % 3)); // 2
// Increment and Decrement
Long counter = 1000000000L;
counter++;
System.debug('After increment: ' + counter); // 1000000001
counter--;
System.debug('After decrement: ' + counter); // 1000000000
// Compound operations
totalUsers += newUsers;
System.debug('Updated total: ' + totalUsers); // 8250000000
Output
Addition: 8250000000 Subtraction: 7750000000 Multiplication: 16000000000 Division: 4000000000 Modulus: 2 After increment: 1000000001 After decrement: 1000000000 Updated total: 8250000000
Real Salesforce Business Examples
🏢 Business Scenario 1: Global API Request Tracking
A global company tracks the total number of API requests processed across all regions.
Long totalApiRequests = 8456789123L;
Long todaysRequests = 25894567L;
Long updatedTotal = totalApiRequests + todaysRequests;
System.debug('Previous Total: ' + totalApiRequests);
System.debug('Today\'s Requests: ' + todaysRequests);
System.debug('Updated Total: ' + updatedTotal); // 8482683690
// Check if total exceeds 10 billion
if (updatedTotal > 10000000000L) {
System.debug('API requests have exceeded 10 billion!');
} else {
System.debug('API requests are within limit.');
}
Output
Previous Total: 8456789123 Today's Requests: 25894567 Updated Total: 8482683690 API requests are within limit.
A value of this size exceeds the Integer limit, making Long the appropriate choice.
🏢 Business Scenario 2: Large Data Migration
A company migrates data from a legacy system with billions of records.
// Records to migrate
Long legacyRecords = 12500000000L;
Long migratedSoFar = 4500000000L;
// Calculate remaining records
Long remainingRecords = legacyRecords - migratedSoFar;
System.debug('Total Records: ' + legacyRecords);
System.debug('Migrated So Far: ' + migratedSoFar);
System.debug('Remaining: ' + remainingRecords); // 8000000000
// Progress percentage (converted to Long for display)
Long progressPercent = (migratedSoFar * 100) / legacyRecords;
System.debug('Migration Progress: ' + progressPercent + '%'); // 36%
// Estimated time calculation (if 1 million records per day)
Long recordsPerDay = 1000000L;
Long estimatedDays = remainingRecords / recordsPerDay;
System.debug('Estimated days remaining: ' + estimatedDays); // 8000
Output
Total Records: 12500000000 Migrated So Far: 4500000000 Remaining: 8000000000 Migration Progress: 36% Estimated days remaining: 8000
🏢 Business Scenario 3: Cloud Storage Analytics
Track storage usage across Salesforce orgs in bytes.
// Storage in bytes
Long storageUsed = 8796093022208L; // 8 TB
Long storageLimit = 10995116277760L; // 10 TB
// Calculate usage percentage
Long usagePercent = (storageUsed * 100) / storageLimit;
System.debug('Storage Used: ' + storageUsed + ' bytes');
System.debug('Storage Limit: ' + storageLimit + ' bytes');
System.debug('Usage: ' + usagePercent + '%'); // 80%
// Convert to human-readable format (approximate GB)
Long storageGB = storageUsed / (1024 * 1024 * 1024);
System.debug('Storage Used: ' + storageGB + ' GB'); // 8192 GB
// Alert if storage exceeds 90%
if (usagePercent > 90) {
System.debug('Warning: Storage usage exceeds 90%!');
} else {
System.debug('Storage usage is normal.');
}
Output
Storage Used: 8796093022208 bytes Storage Limit: 10995116277760 bytes Usage: 80% Storage Used: 8192 GB Storage usage is normal.
Common Long Operations
| Operator/Method | Description | Example | Result |
|---|---|---|---|
+ | Addition | 5000000000L + 3000000000L | 8000000000L |
- | Subtraction | 5000000000L - 2000000000L | 3000000000L |
* | Multiplication | 5000000000L * 2 | 10000000000L |
/ | Division | 5000000000L / 2 | 2500000000L |
% | Modulus | 5000000000L % 3 | 2L |
++ | Increment | count++ | count + 1 |
-- | Decrement | count-- | count - 1 |
+= | Compound addition | count += 1000000L | count + 1000000 |
Long.valueOf() | Convert to Long | Long.valueOf("9876543210") | 9876543210L |
Long vs Integer
| Feature | Long | Integer |
|---|---|---|
| Memory Size | 64-bit (8 Bytes) | 32-bit (4 Bytes) |
| Minimum Value | -9.2 × 10^18 | -2.1 × 10^9 |
| Maximum Value | 9.2 × 10^18 | 2.1 × 10^9 |
| Use Cases | Very large numbers, global counters | Normal counting, IDs |
| Memory Usage | More memory | Less memory |
| Performance | Slightly slower | Faster |
| When to Use | When value may exceed Integer range | When value fits in Integer range |
| Example | 9000000000L | 9000 |
Long vs Decimal
| Feature | Long | Decimal |
|---|---|---|
| Stores | Whole numbers only | Numbers with decimal places |
| Precision | Exact whole numbers | High precision decimals (up to 38 digits) |
| Range | 9.2 × 10^18 | 38 digits total |
| Suitable for | Counting, IDs, counters | Currency, financial calculations |
| Example | 9876543210L | 9876543210.50 |
Long vs Integer: When to Choose Which
| Situation | Recommended Type | Reason |
|---|---|---|
| Age of an employee | Integer | Fits easily within Integer range |
| Quantity of products | Integer | Normal business quantities are small |
| Opportunity count | Integer | Even large orgs have under 2 billion records |
| Global API request count | Long | Can easily exceed 2.1 billion |
| Very large analytics counter | Long | Billions of analytics events are common |
| Large storage size in bytes | Long | File sizes can be in terabytes |
| Record IDs from external systems | Long | Some systems use 64-bit IDs |
Common Long Methods
Apex provides several useful methods for working with Long values:
Long number = 1234567890L;
// Convert to String
String str = String.valueOf(number);
System.debug('String: ' + str); // "1234567890"
// Parse from String
Long parsed = Long.valueOf("9876543210");
System.debug('Parsed: ' + parsed); // 9876543210
// Compare with another Long
Long another = 9876543210L;
Integer comparison = number.compareTo(another); // -1 (less than)
Boolean isEqual = number == another; // false
// Check if value is null
if (number != null) {
System.debug('Number is not null');
}
// Convert to Decimal (if needed for calculations)
Decimal decimalFromLong = Decimal.valueOf(number);
System.debug('As Decimal: ' + decimalFromLong); // 1234567890.0
// Format with grouping
String formatted = number.format();
System.debug('Formatted: ' + formatted); // "1,234,567,890"
Output
String: 1234567890 Parsed: 9876543210 Number is not null As Decimal: 1234567890.0 Formatted: 1,234,567,890
Common Long Pitfalls & Solutions
| Pitfall | Example | Solution |
|---|---|---|
| Null Pointer Exception | Long x; Long y = x + 5; |
Always initialize: Long x = 0L; or check for null |
| Missing 'L' Suffix | Long value = 5000000000; // Compile error |
Add 'L' suffix: Long value = 5000000000L; |
| Integer Overflow | Integer count = 3000000000; // Compile error |
Use Long: Long count = 3000000000L; |
| Using Long for Currency | Long price = 99.99; |
Use Decimal for currency: Decimal price = 99.99; |
| Comparing Long with Integer | if (longVal == intVal) |
Convert to same type: if (longVal == Long.valueOf(intVal)) |
| Parsing Invalid Strings | Long.valueOf("abc"); |
Use try-catch or validate before parsing |
How Salesforce Stores Long Values
Developer Writes
Long totalRecords = 5000000000L;
│
▼
Compiler Checks
✔ Long Type exists?
✔ Variable name valid?
✔ 'L' suffix present for large values?
│
▼
Memory Allocated
64-bit (8 Bytes)
│
▼
Value Stored in Binary
0100 1010 1001 0001 ... (64-bit representation)
│
▼
Available for Arithmetic Operations
Used for counting, analytics, and storage
Long uses 64-bit storage, allowing it to hold values up to 9.2 quintillion.
Common Salesforce Use Cases
| Business Requirement | Example Value | Use Case |
|---|---|---|
| Total API Requests | 9,800,000,000 | Global API usage tracking |
| Large Data Migration Count | 12,500,000,000 | Bulk data migration projects |
| Analytics Counters | 7,850,000,000 | Event tracking and analytics |
| System Log Entries | 15,300,000,000 | Log management systems |
| Large File Size (Bytes) | 8,796,093,022,208 | Cloud storage management |
| External System IDs | 9,223,372,036 | Integration with external systems |
| GPS Timestamps (Unix time) | 1,700,000,000 | Timestamp storage (within range) |
| Database Record Counts | 5,000,000,000 | Multi-org record tracking |
🔍 Behind the Scenes: Long Processing
Large Numeric Value Detected
Example: 5,000,000,000
│
▼
Compiler Identifies as Long
Requires 64-bit storage
│
▼
64-bit Storage Allocated
8 bytes of memory
│
▼
Arithmetic Processing
Addition, Subtraction, etc.
│
▼
Result Returned
Maintained as Long or converted
Converting Between Long and Other Types
Here are common conversion patterns:
// Integer to Long (safe, no data loss)
Integer intValue = 1000000;
Long longFromInt = Long.valueOf(intValue);
Long longFromInt2 = (Long) intValue; // Implicit conversion
// Long to Integer (possible data loss if value exceeds Integer range)
Long largeLong = 5000000000L;
Integer fromLong = largeLong.intValue(); // WARNING: May lose data!
// String to Long
Long fromString = Long.valueOf("9876543210");
// Long to String
String toString = String.valueOf(largeLong);
// Long to Decimal
Decimal decimalFromLong = Decimal.valueOf(largeLong);
// Decimal to Long (data loss if decimal part exists)
Decimal decimalValue = 123.45;
Long fromDecimal = decimalValue.longValue(); // 123 (truncates decimal)
⚠️ Important: Converting Long to Integer can cause data loss if the Long value exceeds the Integer range. Always check the value before conversion.
✅ Best Practices
- Use Integer for normal counting operations (faster, less memory).
- Use Long only when values may exceed the Integer range (-2.1B to 2.1B).
- Append
Lto large numeric literals when declaring Long values. - Use meaningful variable names such as
totalApiRequests,storageUsed, orrecordCount. - Avoid using Long when Integer is sufficient, as Integer is simpler and uses less memory.
- Always check for null before performing arithmetic operations on Long variables.
- Use
Long.valueOf()for safe string to Long conversion with error handling. - Be cautious when converting Long to Integer - check if value fits in Integer range.
- Use Decimal for financial calculations, not Long.
⚠️ Common Mistakes
- Using Integer for values that exceed its maximum range (causes compile error).
- Forgetting the
Lsuffix when writing large Long literals. - Using Long for currency values instead of Decimal.
- Choosing Long unnecessarily when Integer is sufficient (wastes memory).
- Forgetting that uninitialized Long variables are
null, not 0. - Using
==to compare Long objects without considering null values. - Converting Long to Integer without checking for overflow.
🎯 Interview Tip
Question: When should you use Long instead of Integer in Apex?
Answer: Use Long when a whole number may exceed the Integer range of -2,147,483,648 to 2,147,483,647. Long supports a much larger 64-bit range (up to 9.2 × 10^18) and is commonly used for large counters, global analytics, integrations with external systems, and storage-related values.
Question: What is the purpose of the 'L' suffix in Long literals?
Answer: The L suffix tells the Apex compiler that the numeric literal should be treated as a Long instead of an Integer. Without the suffix, any number outside the Integer range will cause a compilation error. For example, 5000000000L is treated as a Long, while 5000000000 would cause an error.
Question: What happens when you convert a Long to an Integer in Apex?
Answer: Converting a Long to an Integer using longValue.intValue() can cause data loss if the Long value exceeds the Integer range. The value will be truncated modulo 2^32, potentially resulting in incorrect values. Always check if the Long value fits in the Integer range before conversion.
📌 Quick Revision
- ✔ Stores very large whole numbers (64-bit).
- ✔ Uses 64-bit (8-byte) memory allocation.
- ✔ Supports a much larger range than Integer (-9.2 × 10^18 to 9.2 × 10^18).
- ✔ Does not store decimal values (use Decimal for decimals).
- ✔ Commonly used for large counters, analytics, and storage sizes.
- ✔ Append
Lto large numeric literals (e.g.,5000000000L). - ✔ Values within Integer range don't need the
Lsuffix. - ✔ Uninitialized Long variables default to
null. - ✔ Use Integer when possible (less memory, better performance).
- ✔ Common methods:
Long.valueOf(),format(),compareTo().
➡ Next Lesson
In the next lesson, you'll learn about the Boolean data type, which stores only true or false values and is widely used for decision-making, conditional logic, validation, and business rules in Apex.
Practice What You've Learned
Test your understanding with these practice exercises