Primitive Data Types
Learning Content
Last updated: July 21, 2026
Decimal Data Type in Apex
The Decimal data type is used to store numbers that contain decimal values with high precision. It is commonly used in financial calculations, currency values, discounts, taxes, commissions, and percentages where accuracy is extremely important.
Unlike floating-point numbers, Decimal minimizes rounding errors, making it the preferred choice for most Salesforce business applications involving money and calculations.
💡 LearnFrenzy Insight
Whenever you work with money in Salesforce, always prefer Decimal instead of Double. Financial calculations require high precision, and Decimal is specifically designed for this purpose.
Why Do We Need Decimal?
Many Salesforce applications deal with financial information such as Opportunity Amount, Product Price, Tax, Discount, Commission, and Budget. Even a small rounding error can produce incorrect business results.
The Decimal data type helps maintain calculation accuracy, ensuring that financial values remain reliable throughout the application.
| Business Scenario | Why Decimal? |
|---|---|
| Opportunity Amount | Stores currency values accurately. |
| Product Discount | Calculates percentage discounts without precision loss. |
| GST / VAT | Maintains accurate tax calculations. |
| Sales Commission | Computes commission values precisely. |
| Budget Planning | Handles financial planning and forecasting. |
Syntax
Decimal variableName = value;
Example 1: Declaring a Decimal Variable
The following example stores a product price in a Decimal variable.
// Execute Anonymous Window
Decimal productPrice = 1999.99;
System.debug(productPrice);
Output
1999.99
Explanation
Decimalstores numbers with decimal values.1999.99is assigned toproductPrice.System.debug()prints the value in the Debug Log.
Example 2: Calculating Product Discount
Suppose an online shopping application offers a 10% discount on a product priced at ₹25,000.
Decimal price = 25000;
Decimal discount =
price * 10 / 100;
System.debug(discount);
Output
2500
Explanation
- The product price is ₹25,000.
- The discount percentage is 10%.
- The calculated discount is ₹2,500.
🏢 Real Business Scenario
In Salesforce Sales Cloud, every Opportunity stores its revenue amount using a Decimal value.
For example:
- Opportunity Amount
- Expected Revenue
- Forecast Revenue
- Partner Commission
- Sales Discount
All of these values require high precision and are ideal candidates for the Decimal data type.
Example 3: Calculating GST
Let's calculate an 18% GST for a product.
Decimal amount = 50000;
Decimal gst =
amount * 18 / 100;
System.debug(gst);
Output
9000
Example 4: Final Amount After Discount
Decimal amount = 50000;
Decimal discount =
amount * 20 / 100;
Decimal finalAmount =
amount - discount;
System.debug(finalAmount);
Output
40000
Example 5: Average Sales Calculation
Decimal january = 150000.75;
Decimal february = 180000.50;
Decimal march = 210000.25;
Decimal average =
(january + february + march) / 3;
System.debug(average);
Output
180000.50
Example 6: Comparing Decimal Values
Decimal target = 500000;
Decimal achieved = 520000.75;
if(achieved >= target){
System.debug('Target Achieved');
}
else{
System.debug('Target Not Achieved');
}
Output
Target Achieved
Example 7: Decimal in an Apex Class
public class DiscountCalculator {
public static Decimal calculateDiscount(
Decimal amount,
Decimal percentage
){
return amount * percentage / 100;
}
}
Calling the Method
Decimal discount =
DiscountCalculator.calculateDiscount(
75000,
15
);
System.debug(discount);
Output
11250
Decimal vs Integer
| Integer | Decimal |
|---|---|
| Stores whole numbers. | Stores decimal numbers. |
| No fractional values. | Supports fractional values. |
| Used for counts. | Used for currency and financial calculations. |
| Example: 100 | Example: 100.75 |
✅ Best Practice
Use Decimal whenever you are working with currency, tax, discount, commission, or any financial calculation. It provides better precision than floating-point numbers and helps avoid unexpected rounding issues.
⚠️ Common Mistake
Many beginners use Integer for price calculations.
For example:
Integer price = 999.99;
This produces a compile-time error because Integer cannot store decimal values.
🎯 Interview Tip
Question: When should you use Decimal instead of Double in Apex?
Answer: Use Decimal for financial calculations such as currency, discounts, taxes, commissions, and budgets because it provides higher precision and is better suited for business applications.
Quick Revision
- Decimal stores numbers with fractional values.
- It is the preferred data type for currency and financial calculations.
- Decimal provides higher precision than floating-point numbers.
- Common use cases include Opportunity Amount, Discount, Tax, Commission, and Budget calculations.
- Avoid using Integer when decimal values are required.
🚀 Next Section: Double Data Type
You'll learn when to use Double, how it differs from Decimal, precision considerations, scientific calculations, and practical Apex examples.
Double Data Type in Apex
The Double data type is used to store decimal numbers using double-precision floating-point representation. It is suitable for scientific calculations, mathematical formulas, engineering computations, and situations where approximate decimal values are acceptable.
Although both Decimal and Double can store numbers with decimal values, they are designed for different purposes.
In Salesforce development, Decimal is generally preferred for financial calculations, while Double is useful for mathematical and scientific calculations where very large or very small numbers need to be processed efficiently.
💡 LearnFrenzy Insight
Think of Decimal as an accountant and Double as a scientist.
An accountant needs exact values for money.
A scientist often needs very large or very small numbers where tiny precision differences are acceptable.
Why Do We Need Double?
Some applications perform mathematical or scientific calculations where performance is more important than perfect decimal precision.
Examples include:
- GPS Coordinate Calculations
- Distance Calculations
- Temperature Monitoring
- Engineering Measurements
- Physics Simulations
- Machine Learning Calculations
Syntax
Double variableName = value;
Example 1: Declaring a Double Variable
The following example stores a temperature value.
// Execute Anonymous Window
Double temperature = 36.78;
System.debug(temperature);
Debug Log Output
USER_DEBUG [3]|DEBUG|36.78
Explanation
Doublestores decimal values.- It supports floating-point calculations.
- The value is displayed using
System.debug().
Example 2: Calculate Average Temperature
Double monday = 36.4;
Double tuesday = 37.1;
Double wednesday = 35.8;
Double average =
(monday + tuesday + wednesday)/3;
System.debug(average);
Debug Log Output
USER_DEBUG [6]|DEBUG|36.43333333333333
🏢 Real Business Scenario
Suppose your Salesforce application integrates with an IoT device that continuously sends temperature readings from manufacturing equipment.
Since these values are measurements rather than financial amounts, Double is an appropriate choice.
Example 3: GPS Coordinates
Double latitude = 28.613939;
Double longitude = 77.209023;
System.debug(latitude);
System.debug(longitude);
Debug Log Output
USER_DEBUG [4]|DEBUG|28.613939
USER_DEBUG [5]|DEBUG|77.209023
Example 4: Mathematical Calculation
Double radius = 7.5;
Double area =
3.14159 * radius * radius;
System.debug(area);
Debug Log Output
USER_DEBUG [5]|DEBUG|176.7144375
Example 5: Scientific Notation
Double speedOfLight = 3.0E8;
System.debug(speedOfLight);
Debug Log Output
USER_DEBUG [3]|DEBUG|3.0E8
Scientific notation is useful for representing extremely large or extremely small values.
Decimal vs Double
| Feature | Decimal | Double |
|---|---|---|
| Purpose | Financial calculations | Scientific calculations |
| Precision | Very High | Floating Point |
| Currency | ✅ Recommended | ❌ Not Recommended |
| Temperature | Possible | ✅ Better Choice |
| GPS Coordinates | Possible | ✅ Better Choice |
| Opportunity Amount | ✅ Recommended | ❌ Avoid |
When Should You Use Double?
| Use Double | Use Decimal |
|---|---|
| Scientific Calculations | Opportunity Amount |
| GPS Coordinates | Invoice Amount |
| Engineering Data | Tax Calculation |
| Temperature | Commission |
| Sensor Values | Product Price |
✅ Best Practice
For Salesforce business applications involving money, always choose Decimal. Reserve Double for scientific, engineering, and measurement-based calculations.
⚠️ Common Mistake
Using Double to calculate Opportunity Amounts, Invoice Totals, Discounts, or Taxes can introduce floating-point precision differences. Financial calculations should use Decimal.
🎯 Interview Tip
Question: What is the difference between Decimal and Double in Apex?
Answer: Both store decimal values, but Decimal provides higher precision and is ideal for financial calculations, while Double is a floating-point type better suited for scientific and engineering calculations where approximate values are acceptable.
Quick Revision
- Double stores floating-point decimal values.
- It is commonly used for scientific and engineering calculations.
- Use Double for GPS coordinates, sensor readings, and measurements.
- Do not use Double for currency or financial calculations.
- Choose Decimal whenever exact precision is required.
🚀 Next Section: Long Data Type
You'll learn how to work with very large whole numbers, Salesforce record counts, log identifiers, batch processing examples, and practical use cases.
Long Data Type in Apex
The Long data type is used to store very large whole numbers that exceed the storage capacity of the Integer data type. Like Integer, Long stores only whole numbers, but it supports a much larger numeric range.
In Salesforce, Long is useful when working with large record counts, file sizes, timestamps, unique identifiers, batch processing statistics, and integrations that exchange large numeric values.
💡 LearnFrenzy Insight
Think of Integer as a small water tank.
It works perfectly for everyday needs.
But if you're storing water for an entire city, you need a much larger storage tank.
Similarly, when Integer cannot store very large numbers, Apex provides the Long data type.
Why Do We Need Long?
Although Integer is sufficient for most business applications, certain scenarios involve extremely large numbers that exceed its maximum limit.
For example, a data warehouse, IoT platform, banking system, or enterprise integration may process billions of records or generate very large numeric identifiers.
| Business Scenario | Why Long? |
|---|---|
| Large Batch Processing | Store millions or billions of processed records. |
| File Size | Store file size in bytes. |
| Timestamp | Store epoch milliseconds. |
| External System IDs | Support large numeric identifiers. |
| IoT Devices | Store sensor sequence numbers. |
Syntax
Long variableName = value;
Example 1: Declaring a Long Variable
The following example stores a large numeric value.
// Execute Anonymous Window
Long totalPopulation = 8200000000L;
System.debug(totalPopulation);
Debug Log Output
USER_DEBUG [3]|DEBUG|8200000000
Explanation
- Long stores large whole numbers.
- The suffix
Lindicates that the value is of type Long. System.debug()displays the value in the Debug Log.
Example 2: File Size Calculation
Suppose a document management application stores file sizes in bytes.
Long fileSize = 5368709120L;
System.debug(fileSize);
Debug Log Output
USER_DEBUG [3]|DEBUG|5368709120
🏢 Real Business Scenario
Imagine Salesforce integrates with SharePoint or AWS S3 to manage large documents.
The application may need to store file sizes in bytes.
Large file sizes can easily exceed the Integer range, making Long the appropriate data type.
Example 3: Batch Processing Statistics
Long processedRecords = 1500000000L;
System.debug(
'Processed Records = ' + processedRecords
);
Debug Log Output
USER_DEBUG [4]|DEBUG|Processed Records = 1500000000
Example 4: Store Epoch Timestamp
Many REST APIs exchange timestamps in milliseconds since January 1, 1970 (Unix Epoch).
Long epochTime = 1752518400000L;
System.debug(epochTime);
Debug Log Output
USER_DEBUG [3]|DEBUG|1752518400000
This value can later be converted into a readable DateTime if required.
Example 5: Comparing Long Values
Long target = 1000000000L;
Long processed = 1200000000L;
if(processed > target){
System.debug('Target Achieved');
}
else{
System.debug('Target Not Achieved');
}
Debug Log Output
USER_DEBUG [6]|DEBUG|Target Achieved
Integer vs Long
| Feature | Integer | Long |
|---|---|---|
| Stores | Whole Numbers | Very Large Whole Numbers |
| Decimal Values | No | No |
| Typical Usage | Age, Quantity, Count | Large Counts, File Size, Timestamps |
| Requires L Suffix | No | Yes (recommended for large literals) |
When Should You Use Long?
| Use Integer | Use Long |
|---|---|
| Student Count | Population Count |
| Product Quantity | Large File Size |
| Order Count | Epoch Timestamp |
| Age | Batch Processing Statistics |
| Daily Login Count | External Numeric IDs |
✅ Best Practice
Use Integer for normal counting operations because it is simpler and sufficient for most applications.
Use Long only when values can exceed the Integer range or when working with timestamps, large identifiers, or massive datasets.
⚠️ Common Mistake
Do not use Long for decimal values.
For example:
Long amount = 1000.75;
This produces a compile-time error because Long stores only whole numbers.
🎯 Interview Tip
Question: What is the difference between Integer and Long in Apex?
Answer: Both store whole numbers, but Long supports a much larger numeric range and is commonly used for timestamps, large record counts, file sizes, and enterprise integrations involving very large numeric values.
Quick Revision
- Long stores very large whole numbers.
- It does not support decimal values.
- Use Long for timestamps, large counters, file sizes, and external IDs.
- Use Integer for everyday counting operations.
- Append
Lto large numeric literals for clarity.
🚀 Next Section: Boolean & String Data Types
You'll learn Boolean decision-making, String manipulation, built-in String methods, and real-world Salesforce examples with expected outputs.
Boolean Data Type in Apex
The Boolean data type represents one of two possible values: true or false. It is commonly used to make decisions, evaluate conditions, and control the execution flow of an Apex program.
Almost every Salesforce application uses Boolean values to determine whether a condition is satisfied. Examples include checking whether a user is active, whether an Opportunity is Closed Won, whether a record is approved, or whether an Account is eligible for a discount.
💡 LearnFrenzy Insight
Think of a Boolean value as a light switch.
There are only two possible states:
- ON →
true - OFF →
false
Why Do We Need Boolean?
Business applications frequently need to answer questions that have only two possible outcomes.
| Business Question | Boolean Result |
|---|---|
| Is the user active? | true / false |
| Has the Opportunity been closed? | true / false |
| Is the customer eligible for a discount? | true / false |
| Is the promotion approved? | true / false |
| Has payment been received? | true / false |
Syntax
Boolean variableName = true;
Boolean variableName = false;
Example 1: Declaring a Boolean Variable
// Execute Anonymous Window
Boolean isActive = true;
System.debug(isActive);
Debug Log Output
USER_DEBUG [3]|DEBUG|true
Explanation
Booleanstores eithertrueorfalse.- The value
trueis assigned toisActive. System.debug()prints the value in the Debug Log.
Example 2: Using Boolean with if Statement
Boolean isApproved = true;
if(isApproved){
System.debug('Promotion Approved');
}
else{
System.debug('Promotion Pending');
}
Debug Log Output
USER_DEBUG [5]|DEBUG|Promotion Approved
Example 3: Opportunity Status
Boolean isClosedWon = false;
if(isClosedWon){
System.debug('Generate Invoice');
}
else{
System.debug('Opportunity Still Open');
}
Debug Log Output
USER_DEBUG [7]|DEBUG|Opportunity Still Open
🏢 Real Business Scenario
When an Opportunity becomes Closed Won, Salesforce can automatically:
- Create an Order
- Generate an Invoice
- Notify the Finance Team
- Start the Delivery Process
These actions are often controlled using Boolean conditions.
Example 4: Customer Eligibility
Boolean isPremiumCustomer = true;
Boolean eligibleForDiscount =
isPremiumCustomer;
System.debug(
'Discount Eligible = ' +
eligibleForDiscount
);
Debug Log Output
USER_DEBUG [6]|DEBUG|Discount Eligible = true
Example 5: Boolean Expression
Integer orderAmount = 15000;
Boolean freeShipping =
orderAmount >= 10000;
System.debug(freeShipping);
Debug Log Output
USER_DEBUG [5]|DEBUG|true
Boolean Operators
| Operator | Description | Example |
|---|---|---|
| && | Logical AND | a && b |
| || | Logical OR | a || b |
| ! | Logical NOT | !isActive |
Example 6: Logical AND
Boolean paymentReceived = true;
Boolean stockAvailable = true;
if(paymentReceived && stockAvailable){
System.debug(
'Dispatch Order'
);
}
Debug Log Output
USER_DEBUG [8]|DEBUG|Dispatch Order
Example 7: Logical OR
Boolean admin = false;
Boolean manager = true;
if(admin || manager){
System.debug(
'Access Granted'
);
}
Debug Log Output
USER_DEBUG [8]|DEBUG|Access Granted
Example 8: Logical NOT
Boolean isLocked = false;
System.debug(!isLocked);
Debug Log Output
USER_DEBUG [3]|DEBUG|true
Boolean vs Integer vs String
| Data Type | Purpose | Example |
|---|---|---|
| Boolean | Decision Making | true |
| Integer | Whole Numbers | 150 |
| String | Text Values | "LearnFrenzy" |
✅ Best Practice
Give Boolean variables meaningful names that clearly indicate a yes/no condition, such as:
- isActive
- isApproved
- hasPermission
- isClosedWon
- canSubmit
- isEligible
These names make your code much easier to read.
⚠️ Common Mistake
Avoid comparing Boolean variables with == true unnecessarily.
Instead of:
if(isActive == true)
Write:
if(isActive)
This is cleaner, shorter, and follows Apex coding best practices.
🎯 Interview Tip
Question: Where is the Boolean data type commonly used in Salesforce?
Answer: Boolean is widely used in validation logic, decision-making, approval processes, triggers, Flows, permission checks, Opportunity status evaluation, feature flags, and business rule implementation.
Quick Revision
- Boolean stores only two values:
trueandfalse. - It is mainly used for decision-making and conditional logic.
- Boolean works with
if,else, and logical operators such as&&,||, and!. - Use meaningful Boolean variable names to improve readability.
- Avoid unnecessary comparisons like
== true.
🚀 Next Section: String Data Type
You'll learn String creation, concatenation, comparison, built-in String methods, null handling, escape characters, regular expressions, and real Salesforce examples with outputs.
String Support in Apex
One of the most frequently used data types in Salesforce Apex is the String. A String represents a sequence of characters and is used to store textual information such as names, email addresses, phone numbers, addresses, product names, account names, error messages, and API responses.
Since Salesforce stores a significant amount of business information as text, String plays an important role in almost every Apex application. Whether you're validating user input, generating dynamic messages, sending emails, or integrating with external systems, you'll frequently work with String values.
💡 LearnFrenzy Insight
Think of a String as a digital notebook where you can write letters, words, numbers, symbols, or complete sentences. Unlike numeric data types, a String can store almost any readable text.
Why Do We Need String?
Business applications deal with much more than numbers. Customer names, company names, product descriptions, email addresses, order numbers, comments, and support messages are all stored as text.
The String data type enables Apex developers to create, manipulate, compare, and process textual information efficiently.
| Business Data | Example |
|---|---|
| Customer Name | Saurabh Samir |
| Email Address | support@learnfrenzy.com |
| Company Name | LearnFrenzy Technologies |
| Product Name | Salesforce Apex Handbook |
| Error Message | Record already exists. |
| API Response | {"status":"Success"} |
Simple String Example
The following example stores a customer's name in a String variable.
// Execute Anonymous Window
String customerName = 'Rahul Sharma';
System.debug(customerName);
Debug Log Output
USER_DEBUG [3]|DEBUG|Rahul Sharma
In this example, the variable customerName stores text instead of numbers. Apex automatically treats the value enclosed within single quotes as a String.
Real Business Scenario
🏢 Business Example
Imagine a Salesforce CRM application where a sales representative creates a new customer account.
The following information is stored using String values:
- Customer Name
- Company Name
- Email Address
- City
- Country
- Industry
Almost every Salesforce object contains multiple String fields.
Where is String Used in Salesforce?
| Area | Usage |
|---|---|
| Accounts | Account Name, Website, Industry |
| Contacts | First Name, Last Name, Email |
| Cases | Subject, Description |
| Products | Product Name, Product Code |
| Integrations | JSON, XML, REST API Responses |
| Email Services | Email Subject and Body |
✅ Best Practice
Use meaningful variable names such as customerName, emailAddress, productName, or caseSubject. Clear naming improves code readability and maintainability.
🎯 Interview Tip
Question: Why is the String data type important in Apex?
Answer: String is used to store and process textual information such as customer names, email addresses, product names, descriptions, API responses, and error messages. It is one of the most frequently used data types in Salesforce development.
📚 Learn More
In this chapter, we introduced the String data type as one of Apex's core features.
In Chapter 3 – Variables & Data Types, you'll explore String in detail, including:
- String Methods
- String Comparison
- String Concatenation
- Escape Characters
- StringBuilder
- Regular Expressions (Regex)
- Null Handling
- Real Salesforce Examples
- 30+ Practical Programs
Practice What You've Learned
Test your understanding with these practice exercises