Apex programming Examples

Apex programming Examples

On January 6, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Apex programming Examples
Apex programming examples

Table of Contents

Here we will use the Developer Edition Environment of salesforce and In this example, we will discuss object and field creation in Salesforce and how to use them in code for implementing business logic.

Apex Trigger for Account

An Apex Trigger for Account is a custom script written in Salesforce’s Apex programming language, designed to execute automated actions before or after certain events occur on Account records in Salesforce. These events can include creating a new account, updating an existing account, or deleting an account. The trigger essentially listens for specific changes or actions performed on Account objects and then executes predefined logic, allowing for complex business processes to be automated directly within the Salesforce platform.

Checkout: Loops in Salesforce Apex

For example, an Apex Trigger could be configured to automatically update related records, enforce data validation rules, or even integrate with external systems when an Account record is modified. This level of customization makes Apex Triggers a powerful tool for tailoring Salesforce’s standard Account functionality to meet unique business requirements, ensuring data integrity, and enhancing overall system efficiency.

CRS Info Solutions offers a comprehensive and dynamic Salesforce online course for beginners, career building program for beginners, covering admin, developer, and LWC concepts. This course features immersive real-time projects, interactive hands-on learning, detailed daily notes, essential Salesforce admin interview questions and answers, thorough certification preparation, and strategic job prep guidance. Join their inspiring free demo to embark on an exciting Salesforce journey with expert mentorship and unlock your full potential in the Salesforce ecosystem. Enroll for a free demo today!

Checkout: DML statements in Salesforce

This trigger automatically updates a custom field NumberOfContacts on the Account object whenever a new contact is added or an existing one is deleted.

Finance & Banking Apex Program Examples

1: Calculating Loan Interest

This snippet demonstrates how to calculate the interest on a loan given the principal amount, annual interest rate, and the loan term in years.

trigger UpdateContactCount on Contact (after insert, after delete) {
    Set<Id> accountIds = new Set<Id>();
    
    if (Trigger.isInsert) {
        for (Contact c : Trigger.new) {
            accountIds.add(c.AccountId);
        }
    }
    if (Trigger.isDelete) {
        for (Contact c : Trigger.old) {
            accountIds.add(c.AccountId);
        }
    }

    List<Account> accountsToUpdate = [SELECT Id, NumberOfContacts__c 
                                      FROM Account 
                                      WHERE Id IN :accountIds];
    for (Account a : accountsToUpdate) {
        a.NumberOfContacts__c = [SELECT count() 
                                 FROM Contact 
                                 WHERE AccountId = a.Id];
    }

    update accountsToUpdate;
}

The first program, LoanCalculator , is designed to compute the total interest payable on a loan over a specified term. The calculateInterest method takes three parameters: the principal amount ( principal ), the annual interest rate ( annualInterestRate ), and the loan term in years ( termYears ). Inside the method, the annual interest rate is first converted from a percentage to a decimal by dividing it by 100. Then, using the formula Interest = Principal * Rate * Time , the interest is calculated by multiplying the principal amount by the annual interest rate and then by the number of years in the loan term. This calculated interest is returned as the method’s output.

Read more: Classes – Salesforce Apex

To illustrate how this works, consider an example where the principal is $10,000, the annual interest rate is 5%, and the loan term is 3 years. When the calculateInterest method is called with these values, it computes the interest as $1,500. This output is displayed in the debug log, showing the total interest to be paid over the loan period.

Snippet 2: Banking Transaction Processing

This snippet showcases a simple method to process a banking transaction between two accounts.

public class BankTransaction {
    public static void transferAmount(Id fromAccountId, Id toAccountId, Decimal amount) {
        // Retrieve the accounts involved in the transaction
        Account fromAccount = [SELECT Id, Name, Balance__c FROM Account WHERE Id = :fromAccountId];
        Account toAccount = [SELECT Id, Name, Balance__c FROM Account WHERE Id = :toAccountId];
        
        // Check if the fromAccount has sufficient balance
        if (fromAccount.Balance__c >= amount) {
            // Deduct the amount from the source account
            fromAccount.Balance__c -= amount;
            // Add the amount to the destination account
            toAccount.Balance__c += amount;
            
            // Update the accounts in the database
            update new List<Account>{fromAccount, toAccount};
            
            System.debug('Transaction successful: ' + amount + ' transferred from ' + fromAccount.Name + ' to ' + toAccount.Name);
        } else {
            System.debug('Transaction failed: Insufficient balance in ' + fromAccount.Name);
        }
    }
}

// Example usage
Id fromAccountId = '0011k00002xxxxxxx';
Id toAccountId = '0011k00002yyyyyyy';
Decimal amount = 500; // $500

BankTransaction.transferAmount(fromAccountId, toAccountId, amount);

The second program, BankTransaction , is a basic implementation of a banking transaction system where money is transferred between two accounts. The transferAmount method takes three parameters: the ID of the source account ( fromAccountId ), the ID of the destination account ( toAccountId ), and the amount to be transferred ( amount ). The method begins by retrieving the account records for both the source and destination accounts using SOQL queries.

Read more: SOSL Banking & Finance Examples

Once the accounts are fetched, the method checks if the source account has sufficient balance to cover the transfer amount. If the balance is adequate, the specified amount is deducted from the source account’s balance and added to the destination account’s balance. Both account records are then updated in the database to reflect the new balances. A debug log message confirms the successful transaction, including the amount transferred and the names of the involved accounts. If the source account does not have enough balance, a failure message is logged instead.

For example, if the source account has an ID of 0011k00002xxxxxxx , the destination account has an ID of 0011k00002yyyyyyy , and the amount to be transferred is $500, calling the transferAmount method with these parameters will attempt to perform the transfer. If successful, it updates the account balances and logs a confirmation message; otherwise, it logs an error due to insufficient funds.

Read more: SOQL in Apex with code example

Healthcare and Life Sciences Apex Program Examples

1: Calculating BMI (Body Mass Index)

public class HealthCalculator {
    // Method to calculate BMI given weight in kilograms and height in meters
    public static Decimal calculateBMI(Decimal weightKg, Decimal heightM) {
        // BMI formula: BMI = weight (kg) / (height (m) ^ 2)
        Decimal bmi = weightKg / (heightM * heightM);
        return bmi;
    }
}

// Example usage
Decimal weight = 70; // 70 kg
Decimal height = 1.75; // 1.75 meters

Decimal bmi = HealthCalculator.calculateBMI(weight, height);
System.debug('Calculated BMI: ' + bmi); // Output: Calculated BMI: 22.86

The first snippet, HealthCalculator , focuses on calculating the Body Mass Index (BMI) for individuals. BMI is a standard measure used in the healthcare domain to assess whether a person has a healthy body weight relative to their height.

The calculateBMI method in this class takes two parameters: the person’s weight in kilograms ( weightKg ) and their height in meters ( heightM ). Inside the method, the BMI is calculated using the formula BMI = weight / (height * height) , where the weight is divided by the square of the height.

The result, which is the BMI value, is then returned. For instance, if a person weighs 70 kilograms and has a height of 1.75 meters, calling the calculateBMI method with these values will compute their BMI as approximately 22.86. This calculated value is printed to the debug log, providing a quick way to verify the person’s BMI.

Read more: What is Apex?

2: Scheduling Patient Appointments

public class AppointmentScheduler {
    // Method to schedule an appointment for a patient
    public static void scheduleAppointment(Id patientId, Id doctorId, Datetime appointmentDateTime) {
        // Create a new appointment record
        Appointment__c appointment = new Appointment__c();
        appointment.Patient__c = patientId;
        appointment.Doctor__c = doctorId;
        appointment.Appointment_Date_Time__c = appointmentDateTime;
        
        // Insert the appointment record into the database
        insert appointment;
        
        System.debug('Appointment scheduled successfully for patient: ' + patientId);
    }
}

// Example usage
Id patientId = '0031k00002zzzzzzz'; // Example Patient ID
Id doctorId = '0031k00002yyyyyyy'; // Example Doctor ID
Datetime appointmentDateTime = Datetime.newInstance(2024, 6, 15, 10, 0, 0); // June 15, 2024, 10:00 AM

AppointmentScheduler.scheduleAppointment(patientId, doctorId, appointmentDateTime);

The second snippet, AppointmentScheduler , illustrates a method for scheduling patient appointments in a healthcare setting. The scheduleAppointment method accepts three parameters: the ID of the patient ( patientId ), the ID of the doctor ( doctorId ), and the date and time of the appointment ( appointmentDateTime ). The method begins by creating a new instance of the Appointment__c custom object, representing the appointment record. It then assigns the patient and doctor IDs, as well as the appointment date and time, to the respective fields of this record.

Read more: SOQL Logistics Examples

After setting these values, the method inserts the new appointment record into the Salesforce database. If the insertion is successful, a confirmation message is logged, indicating that the appointment has been scheduled successfully. For example, scheduling an appointment for a patient with ID 0031k00002zzzzzzz and a doctor with ID 0031k00002yyyyyyy on June 15, 2024, at 10:00 AM will create a new appointment record with these details.

This snippet demonstrates how to manage and automate the scheduling process for patient appointments in a healthcare application using Salesforce Apex.

Retail and E-commerce Apex Program Example

public class InventoryManager {
    // Method to update inventory when a product is purchased
    public static void updateInventory(Id productId, Integer quantityPurchased) {
        // Retrieve the product record from the database
        Product__c product = [SELECT Id, Name, Inventory_Level__c FROM Product__c WHERE Id = :productId];
        
        // Check if there is sufficient inventory
        if (product.Inventory_Level__c >= quantityPurchased) {
            // Deduct the purchased quantity from the inventory level
            product.Inventory_Level__c -= quantityPurchased;
            
            // Update the product record in the database
            update product;
            
            System.debug('Inventory updated successfully for product: ' + product.Name);
        } else {
            System.debug('Inventory update failed: Insufficient stock for product: ' + product.Name);
        }
    }
}

// Example usage
Id productId = 'a011k00003zzzzzzz'; // Example Product ID
Integer quantityPurchased = 5; // Quantity purchased

InventoryManager.updateInventory(productId, quantityPurchased);

The provided code snippet, InventoryManager , focuses on managing product inventory levels within a retail and e-commerce application. The updateInventory method is designed to update the inventory of a product when a purchase occurs. It takes two parameters: the ID of the product ( productId ) and the quantity purchased ( quantityPurchased ).

Read more: Constants in Salesforce Apex

First, the method retrieves the product record from the Salesforce database using a SOQL query. It selects the product’s ID, name, and current inventory level. Once the product is fetched, the method checks if the available inventory is sufficient to cover the quantity purchased. If there is enough stock, the purchased quantity is subtracted from the current inventory level, and the updated product record is saved back to the database. A success message is logged to indicate that the inventory has been updated. If the stock is insufficient, an error message is logged instead.

For example, if a product with ID a011k00003zzzzzzz has a certain quantity purchased, calling the updateInventory method with this product ID and the quantity will adjust the inventory accordingly. This ensures accurate tracking of product stock levels, crucial for maintaining inventory in retail and e-commerce operations.

Read more: SOSL in Salesforce Apex

Manufacturing Apex Program Example

public class ProductionOrderManager {
    // Method to create a new production order
    public static void createProductionOrder(Id productId, Integer quantityToProduce, Date targetCompletionDate) {
        // Create a new production order record
        Production_Order__c productionOrder = new Production_Order__c();
        productionOrder.Product__c = productId;
        productionOrder.Quantity_To_Produce__c = quantityToProduce;
        productionOrder.Target_Completion_Date__c = targetCompletionDate;
        
        // Insert the production order record into the database
        insert productionOrder;
        
        System.debug('Production order created successfully for product: ' + productId);
    }
}

// Example usage
Id productId = 'a021k00004yyyyyyy'; // Example Product ID
Integer quantityToProduce = 100; // Quantity to produce
Date targetCompletionDate = Date.newInstance(2024, 7, 31); // Target completion date

ProductionOrderManager.createProductionOrder(productId, quantityToProduce, targetCompletionDate);

The provided code snippet, ProductionOrderManager , is designed to help manage production orders within a manufacturing environment. The createProductionOrder method allows users to create a new production order for manufacturing products. It takes three parameters: the ID of the product to be produced ( productId ), the quantity to be produced ( quantityToProduce ), and the target completion date ( targetCompletionDate ).

Dive into these essential Salesforce interview questions and answers for a thorough understanding and profound insights into Salesforce Admin, Developer, Integration, and LWC topics.

Within the method, a new instance of the Production_Order__c custom object is created, which represents the production order record. The method then sets the product ID, the quantity to be produced, and the target completion date fields of the production order record. After setting these values, the new production order record is inserted into the Salesforce database. A debug message confirms the successful creation of the production order.

For example, creating a production order for a product with ID a021k00004yyyyyyy , with a quantity of 100 units and a target completion date of July 31, 2024, will create a new production order record with these details. This example demonstrates a basic way to manage and track production orders, providing a foundation for more complex manufacturing processes and workflows.

Read more: Data types in Salesforce apex

Education Apex Program Example

Managing Student Enrollment in Courses

public class EnrollmentManager {
    // Method to enroll a student in a course
    public static void enrollStudent(Id studentId, Id courseId, Date enrollmentDate) {
        // Create a new enrollment record
        Enrollment__c enrollment = new Enrollment__c();
        enrollment.Student__c = studentId;
        enrollment.Course__c = courseId;
        enrollment.Enrollment_Date__c = enrollmentDate;
        
        // Insert the enrollment record into the database
        insert enrollment;
        
        System.debug('Student enrolled successfully in course: ' + courseId);
    }
}

// Example usage
Id studentId = 'a031k00005zzzzzzz'; // Example Student ID
Id courseId = 'b041k00006yyyyyyy'; // Example Course ID
Date enrollmentDate = Date.today(); // Enrollment date as today's date

EnrollmentManager.enrollStudent(studentId, courseId, enrollmentDate);

The provided code snippet, EnrollmentManager , is designed to help manage student enrollments in courses within an educational environment. The enrollStudent method allows users to enroll a student in a specified course. It takes three parameters: the ID of the student ( studentId ), the ID of the course ( courseId ), and the date of enrollment ( enrollmentDate ).

Read more: Loops in Salesforce Apex

Within the method, a new instance of the Enrollment__c custom object is created, representing the enrollment record. The method then sets the student ID, course ID, and enrollment date fields of the enrollment record. After setting these values, the new enrollment record is inserted into the Salesforce database. A debug message confirms the successful enrollment of the student in the course.

For example, enrolling a student with ID a031k00005zzzzzzz in a course with ID b041k00006yyyyyyy on the current date will create a new enrollment record with these details. This example provides a basic way to manage and track student enrollments, laying the groundwork for more advanced educational management systems and workflows.

Non-Profit Organizations Apex Program Example

Managing Volunteer Assignments in Non-Profit Organizations

This snippet demonstrates a simple method to assign volunteers to events within a non-profit organization context.

public class VolunteerAssignmentManager {
    // Method to assign a volunteer to an event
    public static void assignVolunteer(Id volunteerId, Id eventId, Date assignmentDate) {
        // Create a new volunteer assignment record
        Volunteer_Assignment__c assignment = new Volunteer_Assignment__c();
        assignment.Volunteer__c = volunteerId;
        assignment.Event__c = eventId;
        assignment.Assignment_Date__c = assignmentDate;
        
        // Insert the volunteer assignment record into the database
        insert assignment;
        
        System.debug('Volunteer assigned successfully to event: ' + eventId);
    }
}

// Example usage
Id volunteerId = 'c051k00007zzzzzzz'; // Example Volunteer ID
Id eventId = 'd061k00008yyyyyyy'; // Example Event ID
Date assignmentDate = Date.today(); // Assignment date as today's date

VolunteerAssignmentManager.assignVolunteer(volunteerId, eventId, assignmentDate);

The provided code snippet, VolunteerAssignmentManager , is designed to help manage volunteer assignments within a non-profit organization. The assignVolunteer method allows users to assign a volunteer to a specific event. It takes three parameters: the ID of the volunteer ( volunteerId ), the ID of the event ( eventId ), and the date of the assignment ( assignmentDate ).

Read more: String class and string methods in Salesforce Apex

Within the method, a new instance of the Volunteer_Assignment__c custom object is created, which represents the volunteer assignment record. The method sets the volunteer ID, event ID, and assignment date fields of this record. After setting these values, the new volunteer assignment record is inserted into the Salesforce database. A debug message confirms the successful assignment of the volunteer to the event.

For example, assigning a volunteer with ID c051k00007zzzzzzz to an event with ID d061k00008yyyyyyy on the current date will create a new volunteer assignment record with these details. This example provides a basic way to manage and track volunteer assignments, which is crucial for organizing and coordinating events in non-profit organizations.

Real Estate Apex Program Example

Managing Property Listings in Real-Estate

This snippet demonstrates a simple method to create and manage property listings within a real-estate context.

public class PropertyListingManager {
    // Method to create a new property listing
    public static void createPropertyListing(String propertyName, String propertyAddress, Decimal propertyPrice, Date listingDate) {
        // Create a new property listing record
        Property_Listing__c propertyListing = new Property_Listing__c();
        propertyListing.Name = propertyName;
        propertyListing.Address__c = propertyAddress;
        propertyListing.Price__c = propertyPrice;
        propertyListing.Listing_Date__c = listingDate;
        
        // Insert the property listing record into the database
        insert propertyListing;
        
        System.debug('Property listing created successfully: ' + propertyName);
    }
}

// Example usage
String propertyName = 'Ocean View Apartment'; // Example Property Name
String propertyAddress = '123 Seaside Blvd, Miami, FL'; // Example Property Address
Decimal propertyPrice = 750000; // Property Price
Date listingDate = Date.today(); // Listing date as today's date

PropertyListingManager.createPropertyListing(propertyName, propertyAddress, propertyPrice, listingDate);

The provided code snippet, PropertyListingManager , is designed to help manage property listings within a real-estate environment. The createPropertyListing method allows users to create a new property listing. It takes four parameters: the name of the property ( propertyName ), the address of the property ( propertyAddress ), the price of the property ( propertyPrice ), and the date the property is listed ( listingDate ).

Readmore: Decision Making in Salesforce Apex

Within the method, a new instance of the Property_Listing__c custom object is created, representing the property listing record. The method sets the property name, address, price, and listing date fields of this record. After setting these values, the new property listing record is inserted into the Salesforce database. A debug message confirms the successful creation of the property listing.

For example, creating a property listing for “Ocean View Apartment” located at “123 Seaside Blvd, Miami, FL,” priced at $750,000, and listed on the current date will create a new property listing record with these details. This example provides a basic way to manage and track property listings, which is essential for real-estate operations.

Telecommunications Apex Program Example

Managing Customer Subscriptions in Telecom

This snippet demonstrates a simple method to create and manage customer subscriptions within a telecom context.

public class SubscriptionManager {
    // Method to create a new customer subscription
    public static void createSubscription(Id customerId, String planName, Date startDate, Integer durationMonths) {
        // Create a new subscription record
        Subscription__c subscription = new Subscription__c();
        subscription.Customer__c = customerId;
        subscription.Plan_Name__c = planName;
        subscription.Start_Date__c = startDate;
        subscription.Duration_Months__c = durationMonths;
        subscription.End_Date__c = startDate.addMonths(durationMonths);
        
        // Insert the subscription record into the database
        insert subscription;
        
        System.debug('Subscription created successfully for customer: ' + customerId);
    }
}

// Example usage
Id customerId = 'a071k00009zzzzzzz'; // Example Customer ID
String planName = 'Unlimited Data Plan'; // Example Plan Name
Date startDate = Date.today(); // Subscription start date as today's date
Integer durationMonths = 12; // Duration of the subscription in months

SubscriptionManager.createSubscription(customerId, planName, startDate, durationMonths);

The provided code snippet, SubscriptionManager , is designed to help manage customer subscriptions within a telecom environment. The createSubscription method allows users to create a new subscription for a customer. It takes four parameters: the ID of the customer ( customerId ), the name of the subscription plan ( planName ), the start date of the subscription ( startDate ), and the duration of the subscription in months ( durationMonths ).

Checkout: Interfaces – Salesforce Apex

Within the method, a new instance of the Subscription__c custom object is created, representing the subscription record. The method sets the customer ID, plan name, start date, and duration fields of this record. It also calculates the end date of the subscription by adding the duration in months to the start date. After setting these values, the new subscription record is inserted into the Salesforce database. A debug message confirms the successful creation of the subscription.

Dive into these essential Salesforce interview questions and answers for a thorough understanding and profound insights into Salesforce Admin, Developer, Integration, and LWC topics.

For example, creating a subscription for a customer with ID a071k00009zzzzzzz for the “Unlimited Data Plan,” starting on the current date and lasting for 12 months, will create a new subscription record with these details. This example provides a basic way to manage and track customer subscriptions, which is essential for telecom operations.

Opportunity Management

An Apex Class for Opportunity Management is a structured collection of code that encapsulates specific functions or logic related to managing Opportunity records in Salesforce. This custom class can define methods to automate complex business processes, manipulate data, or integrate with external systems, all centered around the Opportunity object. By creating methods within this class, developers can perform operations like updating opportunity stages, calculating discounts, or aggregating data across related records, directly aligning with business workflows.

You can explore all the String methods in Apex, and learn those examples for each method.

Utilizing an Apex Class for Opportunity Management allows for a more organized and modular approach to handling business logic in Salesforce. It not only enhances code maintainability but also allows for reusability and clearer separation of concerns. For instance, a method within this class can be invoked by triggers, batch jobs, or even from the Salesforce UI through Visualforce or Lightning Components, making it a versatile and integral part of the Salesforce development ecosystem.

This class includes a method that closes all open opportunities related to an account as ‘Lost’.

public class OpportunityManager {
    public static void closeOpportunitiesAsLost(String accountId) {
        List<Opportunity> opportunities = [SELECT Id, StageName 
                                           FROM Opportunity 
                                           WHERE AccountId = :accountId 
                                           AND IsClosed = false];

        for (Opportunity opp : opportunities) {
            opp.StageName = 'Closed Lost';
        }

        update opportunities;
    }
}

Batch Apex for Data Cleanup

Batch Apex for Data Cleanup is a specialized use of Salesforce’s Batch Apex, a powerful tool designed to handle large data sets by processing records in small batches. Specifically tailored for data maintenance tasks, Batch Apex for Data Cleanup allows developers to define complex and resource-intensive operations that identify, process, and delete outdated or irrelevant records from the Salesforce database. This is particularly useful for maintaining data quality and adhering to storage limits, especially in large-scale Salesforce environments where data accumulates rapidly.

Read more: Objects – Salesforce Apex

With Batch Apex for Data Cleanup, the job is divided into manageable chunks, ensuring that the operations do not exceed Salesforce’s governor limits, which are in place to optimize performance and resource usage. The process involves querying the necessary records, performing the cleanup operation (like deleting or archiving), and then iterating over the batches until all the targeted data is processed. This method is not only efficient but also offers the ability to schedule cleanup operations, monitor job progress, and handle exceptions gracefully, making it an essential tool for maintaining a clean and efficient Salesforce instance.

This batch class finds and deletes old records from a custom object MyCustomObject__c .

public class OpportunityManager {
    public static void closeOpportunitiesAsLost(String accountId) {
        List<Opportunity> opportunities = [SELECT Id, StageName 
                                           FROM Opportunity 
                                           WHERE AccountId = :accountId 
                                           AND IsClosed = false];

        for (Opportunity opp : opportunities) {
            opp.StageName = 'Closed Lost';
        }

        update opportunities;
    }
}

Test Class for Apex Method

A Test Class for Apex Method in Salesforce is a framework for ensuring that your Apex code behaves as expected and adheres to the platform’s quality standards. It’s a collection of test methods specifically written to verify the logic of your Apex code by invoking the methods in your classes and checking that the outcomes are as anticipated. These test classes are essential for identifying any issues or bugs before the code is deployed to production. They also play a crucial role in fulfilling Salesforce’s code coverage requirement, which mandates that a certain percentage of your Apex code must be covered by tests to ensure robustness and reliability.

Read more: Methods – Salesforce Apex

Writing a Test Class involves creating scenarios to test each unit of functionality in your Apex code, simulating different conditions, and asserting that the code responds correctly. This not only includes testing for expected outcomes but also handling unexpected or edge cases, ensuring that your application is stable and behaves consistently under various circumstances. Test classes in Salesforce are isolated from your actual data and configurations, meaning they allow for safe testing without affecting your live data. This isolation emphasizes the importance of preparing test data within your test classes to ensure your tests are comprehensive and reliable.

This is a test class for a simple Apex method that adds two numbers. It’s crucial to write test classes to ensure your Apex code works as expected and to meet Salesforce’s code coverage requirements.

@isTest
private class MathTest {
    static testMethod void testAddTwoNumbers() {
        Integer sum = MathClass.addNumbers(5, 3);
        System.assertEquals(8, sum, 'The sum of 5 and 3 should be 8');
    }
}

public class MathClass {
    public static Integer addNumbers(Integer a, Integer b) {
        return a + b;
    }
}

Top 5 Multiple Choice Questions for Salesforce Apex Examples

  1. What is the primary purpose of an Apex Trigger in Salesforce?
    • A) To generate reports and dashboards
    • B) To automatically perform an action before or after data manipulation
    • C) To customize the Salesforce UI
    • D) To integrate Salesforce with external systems
  2. In a Batch Apex class for data cleanup, what is the purpose of the ‘start’ method?
    • A) To define the batch size
    • B) To execute the batch job
    • C) To specify the records to be processed by the batch job
    • D) To summarize the results of the batch job
  3. Which statement about test classes in Apex is true?
    • A) Test classes are optional and not necessary for deployment.
    • B) Test classes can modify data in your production org.
    • C) Test classes help verify the logic of your Apex code and are required to meet code coverage.
    • D) Test classes are used to change user permissions and profiles.
  4. In Apex, what is the purpose of using the ‘Database.QueryLocator’ in a batch Apex class?
    • A) To update records in the database
    • B) To locate and fix database errors
    • C) To efficiently process large sets of records by dividing them into smaller batches
    • D) To locate a specific record in the database without using SOQL
  5. What is the result of using the ‘delete’ DML statement in a Batch Apex class for data cleanup?
    • A) It creates a backup of the records before deleting.
    • B) It permanently removes the specified records from the database.
    • C) It marks the records as deleted, but they can be restored from the Recycle Bin.
    • D) It flags the records for review before the actual deletion.

Answers:
1. B
2. C
3. C
4. C
5. B

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training in Hyderabad to gain practical, hands-on experience, real-time projects included. Our training covers all essential aspects of Salesforce Admin, Developer, LWC, ensuring comprehensive learning, providing daily notes, interview questions, certification preparation and job prep guidance.

With expert instructors and a detailed curriculum, CRS Info Solutions is committed to your success in the Salesforce ecosystem with our Career Building program. Whether you are a beginner or looking to advance your skills, they offer the guidance and resources you need.

Enroll for free demo today!

You can read Salesforce Apex Environment and the next article Salesforce Apex Data Types.

Comments are closed.