Integer
Learning Content
Last updated: July 21, 2026
Integer Data Type
The Integer data type is used to store whole numbers without decimal places. It is one of the most frequently used primitive data types in Apex because many business operations involve counting, numbering, or performing arithmetic on whole values.
Examples include the number of products ordered, quantity in inventory, employee age, customer loyalty points, or the total number of Opportunities associated with an Account.
💡 LearnFrenzy Insight
Imagine counting students in a classroom. You would say:
- 25 Students
- 120 Books
- 18 Computers
You would never count 25.75 students. Whenever the value represents a complete number with no decimal portion, Integer is usually the correct choice.
What is an Integer?
An Integer stores signed whole numbers (both positive and negative) without any decimal point. In Apex, Integer is a 32-bit signed two's complement integer, which means it can represent values from -2,147,483,648 to 2,147,483,647.
Integer quantity = 100; Integer score = 95; Integer temperature = -8; Integer zeroValue = 0; // Zero is also a valid Integer
Integer Range
An Integer occupies 32 bits (4 bytes) of memory and supports the following range:
| Property | Value |
|---|---|
| Minimum Value | -2,147,483,648 |
| Maximum Value | 2,147,483,647 |
| Memory Size | 32-bit (4 Bytes) |
| Default Value | 0 (when declared but not initialized) |
⚠️ Important Note on Range: If you try to store a value outside this range, Apex will throw a System.IntegerException at runtime. For larger numbers, use the Long data type.
Variable Declaration & Initialization
You can declare and initialize Integer variables in several ways:
// Method 1: Declaration with initialization Integer totalEmployees = 350; // Method 2: Declaration without initialization (defaults to null) Integer totalProducts; totalProducts = 1200; // Initialization later // Method 3: Multiple declarations in one line (not recommended) Integer a = 10, b = 20, c = 30; // Method 4: Using the 'new' keyword (rarely used) Integer number = new Integer(100);
📝 Key Points:
- Uninitialized Integer variables default to
null, not 0. - Always initialize variables before using them in calculations to avoid null pointer exceptions.
- Use descriptive names like
availableSeatsinstead ofasorx.
Basic Arithmetic Operations
Integers support all standard arithmetic operations. Here's a complete example:
Integer a = 20;
Integer b = 5;
// Basic Arithmetic
System.debug('Addition: ' + (a + b)); // 25
System.debug('Subtraction: ' + (a - b)); // 15
System.debug('Multiplication: ' + (a * b)); // 100
System.debug('Division: ' + (a / b)); // 4
System.debug('Modulus: ' + (a % b)); // 0
// Order of Operations (PEMDAS)
Integer result = 10 + 5 * 2; // 20 (multiplication first)
Integer result2 = (10 + 5) * 2; // 30 (parentheses first)
Output
25 15 100 4 0
Increment & Decrement Operations
Increment (++) and decrement (--) operators are used to increase or decrease an Integer value by 1:
Integer count = 10;
// Post-increment (returns original value, then increments)
Integer result1 = count++; // result1 = 10, count = 11
// Pre-increment (increments first, then returns new value)
Integer result2 = ++count; // count = 12, result2 = 12
// Post-decrement
Integer result3 = count--; // result3 = 12, count = 11
// Pre-decrement
Integer result4 = --count; // count = 10, result4 = 10
System.debug('Final count: ' + count); // 10
Output
11 10
💡 Pro Tip: Use count++ when you need the current value first, and ++count when you need the updated value immediately.
Common Integer Operations
| Operator | Description | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 5 | 15 |
| - | Subtraction | 20 - 3 | 17 |
| * | Multiplication | 5 * 6 | 30 |
| / | Division (integer) | 20 / 4 | 5 |
| % | Modulus (remainder) | 10 % 3 | 1 |
| ++ | Increment by 1 | count++ | count + 1 |
| -- | Decrement by 1 | count-- | count - 1 |
| += | Compound addition | count += 5 | count + 5 |
| -= | Compound subtraction | count -= 3 | count - 3 |
Real Salesforce Business Example
🏢 Business Scenario 1: Daily Opportunity Limit
A company limits every sales representative to creating a maximum of 100 Opportunities per day.
Integer opportunitiesCreated = 75;
Integer maximumLimit = 100;
Integer remaining = maximumLimit - opportunitiesCreated;
System.debug('Remaining Opportunities: ' + remaining); // 25
// Check if the rep has reached the limit
if (opportunitiesCreated >= maximumLimit) {
System.debug('Daily limit reached. Cannot create more opportunities.');
} else {
System.debug('You can create ' + remaining + ' more opportunities today.');
}
Output
Remaining Opportunities: 25 You can create 25 more opportunities today.
🏢 Business Scenario 2: Inventory Management
// Inventory tracking
Integer availableStock = 150;
Integer orderQuantity = 27;
// Calculate remaining stock
Integer remainingStock = availableStock - orderQuantity;
System.debug('Available: ' + availableStock);
System.debug('Ordered: ' + orderQuantity);
System.debug('Remaining: ' + remainingStock);
// Check if order can be fulfilled
if (orderQuantity <= availableStock) {
System.debug('Order can be fulfilled.');
} else {
System.debug('Insufficient stock.');
}
Output
Available: 150 Ordered: 27 Remaining: 123 Order can be fulfilled.
Integer vs Decimal vs Double
| Feature | Integer | Decimal | Double |
|---|---|---|---|
| Stores | Whole numbers | Decimal values (high precision) | Decimal values (lower precision) |
| Precision | Exact (no decimals) | High precision (38 digits) | Approximate (15-16 digits) |
| Best For | Counting, indexing, IDs | Currency, financial calculations | Scientific calculations |
| Example | 150 | 150.75 | 3.14159 |
| Memory | 4 bytes | Variable (up to 16 bytes) | 8 bytes |
How Salesforce Stores an Integer
Developer Writes
Integer quantity = 50;
│
▼
Compiler Checks
✔ Data Type exists?
✔ Variable name valid?
✔ Value compatible?
│
▼
Memory Allocated
32 Bits (4 Bytes)
│
▼
Value Stored in Binary
50 → 0000 0000 0011 0010
│
▼
Program Uses Value
Perform operations as needed
After program execution, memory is automatically freed by the garbage collector.
Common Integer Use Cases in Salesforce
| Business Requirement | Integer Example | Use Case |
|---|---|---|
| Number of Contacts | Integer contactCount = 250; | Counting related records |
| Product Quantity | Integer quantity = 12; | Inventory management |
| Remaining Leave Days | Integer leaveDays = 15; | HR management |
| Survey Score | Integer score = 92; | Performance evaluation |
| Customer Loyalty Points | Integer points = 500; | Rewards program |
| Page Number | Integer pageNumber = 3; | Pagination |
| Discount Percentage | Integer discount = 15; | Pricing calculations |
Common Integer Methods
Apex provides several useful methods for working with Integer values:
Integer number = 123;
// Convert to String
String numberStr = number.format(); // "123"
// Compare with another Integer
Integer another = 456;
Boolean isEqual = number == another; // false
Integer max = Integer.max(number, another); // 456
Integer min = Integer.min(number, another); // 123
// Parse String to Integer
Integer parsed = Integer.valueOf("789"); // 789
// Check if value is null
if (number != null) {
System.debug('Number is not null');
}
// ValueOf with null handling
Integer safeValue = Integer.valueOf('123'); // Returns 123
💡 Pro Tip: Always use Integer.valueOf() with validation or try-catch when parsing user input to avoid runtime exceptions.
Common Integer Pitfalls & Solutions
| Pitfall | Example | Solution |
|---|---|---|
| Null Pointer Exception | Integer x; Integer y = x + 5; |
Always initialize: Integer x = 0; or check for null |
| Integer Overflow | Integer max = 2147483647 + 1; |
Use Long for larger values |
| Division Precision Loss | Integer result = 5 / 2; // Returns 2 |
Use Decimal for decimal results |
| Currency Calculations | Integer amount = 99 / 10; |
Never use Integer for money - use Decimal |
🔍 Behind the Scenes
Integer value = 75;
│
▼
Memory Reserved
32 Bits (4 Bytes)
│
▼
Binary Representation
75 → 01001011
│
▼
Arithmetic Operations
Add, Subtract, Multiply, etc.
│
▼
Result Returned
The final calculated value
✅ Best Practices
- Use Integer only for whole numbers without decimal points.
- Use meaningful, descriptive variable names (e.g.,
totalEmployees,productQuantity). - Always initialize Integer variables to avoid null pointer exceptions.
- Prefer Decimal for currency, percentages, and financial calculations.
- Check calculations that might exceed the Integer range and use Long when necessary.
- Use
==for equality comparison between Integers (not.equals()). - Consider using wrapper methods like
Integer.valueOf()for string parsing with error handling.
⚠️ Common Mistakes
- Using Integer to store decimal values (e.g.,
Integer price = 10.99;causes an error). - Ignoring Integer overflow when dealing with very large numbers.
- Using Integer for monetary calculations - always use Decimal.
- Using
==to compare Integer objects without considering null values. - Dividing two Integers and expecting a decimal result without casting.
- Forgetting that uninitialized Integers are
null, not 0.
🎯 Interview Tip
Question: When should you use Integer instead of Long?
Answer: Use Integer when the value fits within the 32-bit range (-2,147,483,648 to 2,147,483,647) and you're working with whole numbers. Use Long when there's a possibility of exceeding this range or when working with very large numbers like record counts in large orgs.
Question: What happens when you divide two Integers in Apex?
Answer: Apex performs integer division and truncates (not rounds) any decimal portion. For example, 5 / 2 returns 2, not 2.5. For decimal results, cast to Decimal or use Decimal data type.
📌 Quick Revision
- ✔ Stores whole numbers only (no decimal points).
- ✔ Uses 32-bit (4-byte) memory allocation.
- ✔ Supports positive and negative values in range: -2,147,483,648 to 2,147,483,647.
- ✔ Commonly used for counts, quantities, scores, and limits.
- ✔ Supports arithmetic operators: +, -, *, /, %, ++, --, and compound assignments.
- ✔ Use Long instead if the value may exceed the Integer range.
- ✔ Use Decimal for currency and precise decimal calculations.
- ✔ Uninitialized Integer variables default to
null.
➡ Next Lesson
In the next lesson, you'll explore the Decimal data type in detail. You'll learn:
- Why Decimal is preferred for currency and financial calculations.
- How Decimal differs from Integer and Double.
- Real-world examples of Decimal in Salesforce business applications.
- Best practices for handling precise decimal calculations.
Practice What You've Learned
Test your understanding with these practice exercises