Apex workbook

1. What is Apex?

Apex is a programming language developed by Salesforce for customizing and extending the Salesforce platform. It allows developers to create custom business logic, automation, and integrate with external systems.

2. How do you define a variable in Apex?

   Integer myNumber = 10;

   String myText = ‘Hello, World!’;

3. What are data types in Apex?

Data types in Apex define the type of value a variable can hold. Examples include Integer, String, Boolean, Date, and more.

4. Explain the difference between primitive and complex data types in Apex.

Primitive data types hold a single value (e.g., Integer, Boolean), while complex data types can hold multiple values (e.g., List, Set, Map).

5. What is a trigger? Provide an example.

A trigger in Apex is a piece of code that runs before or after specific events occur in Salesforce, such as creating, updating, or deleting records.

  
   trigger OpportunityTrigger on Opportunity (before insert) {
       for (Opportunity opp : Trigger.new) {
           opp.Amount *= 1.1;
       }
   }

6. What types of triggers are there in Salesforce?

There are two types of triggers in Salesforce: Before Triggers and After Triggers. They can fire on different events, such as before insert or after update.

7. Explain the difference between a Trigger and a Class in Apex.

Triggers are executed based on specific events in Salesforce, while classes contain methods and logic that can be invoked from other parts of the application.

8. What are context variables in a Trigger?

Context variables (like `Trigger.new`, `Trigger.old`, etc.) hold the records that caused the trigger to fire. They provide access to the records being processed.

9. How can you handle exceptions in Apex?

Apex uses try-catch blocks to handle exceptions:

   
   try {
       // Code that might throw an exception
   } catch (Exception e) {
       System.debug('An exception occurred: ' + e.getMessage());
   }
   

10. What are SOQL and SOSL? Provide examples.

SOQL (Salesforce Object Query Language) is used to query records in Salesforce, while SOSL (Salesforce Object Search Language) is used for searching across multiple objects.

// SOQL example
List<Account> accounts = [SELECT Name, Industry FROM Account WHERE Industry = 'Technology'];

 // SOSL example
List<List<SObject>> searchResults = [FIND 'Acme' IN ALL FIELDS RETURNING Account(Name), Contact(FirstName, LastName)];

11. What is the difference between SOQL and SOSL?

SOQL is used for querying specific records from a single object, while SOSL is used for searching across multiple objects to find relevant records.

12. What is the LIMIT keyword used for in SOQL?

The LIMIT keyword is used to restrict the number of records returned by a SOQL query.

  List<Account> accounts = [SELECT Name FROM Account LIMIT 10];

13. How do you perform DML operations in Apex?

DML (Data Manipulation Language) operations like insert, update, and delete can be performed using statements like `insert`, `update`, and `delete`.

 Account newAccount = new Account(Name = 'New Account');
    insert newAccount;

    newAccount.Name = 'Updated Account';
    update newAccount;

    delete newAccount;
   

14. What are Governor Limits in Salesforce?

Governor Limits are Salesforce’s way of ensuring that resources are fairly distributed among all users. They restrict the amount of data and resources a piece of Apex code can consume.

15. Explain the concept of Batch Apex.

Batch Apex allows you to process large amounts of data in small, manageable chunks to avoid hitting governor limits.

   
    public class MyBatchClass implements Database.Batchable<sObject> {
        public Database.QueryLocator start(Database.BatchableContext bc) {
            return Database.getQueryLocator('SELECT Id FROM Account');
        }
        public void execute(Database.BatchableContext bc, List<Account> scope) {
            // Process each account in the scope
        }
        public void finish(Database.BatchableContext bc) {
            // Finalization logic
        }
    }

16. What is the purpose of using the @future annotation?

The `@future` annotation is used to mark a method as executing asynchronously in the background. It’s often used for long-running operations that should not block the main execution thread.

  @future
    public static void performAsyncOperation() {
        // Code to be executed asynchronously
    }

17. What is a Scheduled Apex class? Provide an example.

A Scheduled Apex class allows you to schedule a specific method to run at a predefined time.

  public class MyScheduledClass implements Schedulable {
        public void execute(SchedulableContext sc) {
            // Your logic here
        }
    }

18. How can you implement a REST web service in Apex?

You can implement a REST web service in Apex using the `@RestResource` annotation and defining methods with appropriate HTTP methods.

    @RestResource(urlMapping='/MyWebService/*')
    global with sharing class MyRestService {
        @HttpGet
        global static String doGet() {
            return 'Hello, World!';
        }
    }

19. What is a Wrapper Class in Apex?

A Wrapper Class is a custom class that holds multiple related data types or objects in a single container. It’s often used to display complex data in Visualforce pages.

20. What is a Test Class in Apex? Why is it important?

A Test Class is used to test your Apex code and ensure it works as expected. It’s important because Salesforce requires a certain percentage of code coverage by tests before deploying to production.

21. How do you write unit tests in Apex?

Unit tests in Apex are written using methods with the `@isTest` annotation. They help ensure that your code functions correctly and doesn’t break existing functionality.


    @isTest
    private class MyTestClass {
        @isTest
        static void testMethod() {
            // Test logic here
        }
    }

22. What is the purpose of the Test.startTest() and Test.stopTest() methods?

`Test.startTest()` and `Test.stopTest()` methods are used to delimit the start and end of a section of code in a test. This is useful when you want to measure governor limits within a specific context.

23. What is Test data in Apex?

Test data in Apex is data created specifically for test purposes, separate from your actual organization’s data. It’s used to ensure your tests are predictable and isolated.

24. What is Test.setMock() used for in Apex?

`Test.setMock()` is used to associate a mock implementation with a callout. This allows you to simulate callouts in unit tests without actually making real requests.

25. Explain the concept of SeeAllData in test classes.

The `SeeAllData` attribute in test classes controls whether the tests can access data from the organization’s database. It’s generally recommended to avoid using `SeeAllData` and create your own test data.

26. How can you implement a trigger handler framework in Apex?

A trigger handler framework is a design pattern that separates trigger logic from business logic. It often involves creating separate classes to handle trigger events and applying best practices for maintainability.

27. What is Dynamic Apex? Provide an example.

Dynamic Apex allows you to write code that’s determined at runtime. For example, you can use strings to reference fields or objects dynamically.

 String fieldName = 'Name';
    Account acc = new Account();
    acc.put(fieldName, 'New Account');

28. How can you make a callout to an external service using Apex?

You can make callouts using the `Http` class in Apex. This lets you interact with external APIs and services.

HttpRequest req = new HttpRequest();
    req.setEndpoint('https://api.example.com/resource');
    req.setMethod('GET');
    HttpResponse res = new Http().send(req);

29. What is a Future Callout?

A Future Callout is an asynchronous callout made using the `@future(callout=true)` annotation. It allows callouts to be made in contexts where synchronous callouts are not allowed.

   @future(callout=true)
    public static void makeCallout() {
        // Callout logic here
    }

30. What is a Queueable Apex class?

A Queueable Apex class is used to perform asynchronous tasks. It allows you to break up long-running processes into manageable chunks and control the order of execution.

31. Explain the difference between Trigger.old and Trigger.oldMap.

`Trigger.old` is a list of old versions of sObjects, while `Trigger.oldMap` is a map of IDs to old versions of sObjects. `Trigger.oldMap` is useful for efficiently finding old records based on their IDs.

32. How do you work with relationships in SOQL queries?

You can work with relationships in SOQL by using dot notation to traverse through related objects. For example, to query related Contacts of an Account:

    SELECT Name, (SELECT FirstName, LastName FROM Contacts) FROM Account

33. What is a junction object in Salesforce?

A junction object is an object with two master-detail relationships used to create a many-to-many relationship between two objects. It’s often used to model complex relationships.

  • Explain the difference between before insert and after insert triggers.

A “before insert” trigger fires before records are inserted into the database, allowing you to modify the data before it’s saved. An “after insert” trigger fires after records are saved.

35. What is a static variable in Apex?

A static variable is a variable that belongs to a class rather than an instance of the class. It’s shared among all instances of the class and retains its value between method calls.

36. How can you implement a Singleton pattern in Apex?

A Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Here’s an example:

public class Singleton {
        private static Singleton instance;
        private Singleton() {}
        public static Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }

37. What is the difference between Viewstate and Transient variables in Apex?

`Viewstate` variables are retained across multiple requests in Visualforce pages, while `Transient` variables are not persisted between requests.

38. Explain the concept of Apex sharing.

Apex sharing refers to the mechanisms that control access to records in Salesforce. It enforces the organization’s data access and sharing rules.

39. What is a Rollup Summary Field?

A Rollup Summary Field is a custom field on a master record that displays the calculated value of a specified field on its related detail records, such as the sum of related Opportunity amounts on an Account.

40. How do you handle bulk operations in Apex triggers?

To handle bulk operations, ensure your trigger logic can handle multiple records at once. Use loops and collections to process records efficiently.

41. Explain the concept of Schema in Apex.

The Schema namespace in Apex provides metadata information about your Salesforce objects and fields. It allows you to dynamically reference object and field details in your code.

42. What is the purpose of the System.debug() method?

The `System.debug()` method is used to print debug information to the debug logs. It helps in troubleshooting and understanding how your code is executing.

43. How can you work with Date and Time in Apex?

Apex provides the `Date` and `Datetime` data types to work with dates and times. You can perform various operations like adding days, comparing dates, and formatting them.

44. What are Custom Settings in Salesforce?

Custom Settings are custom objects in Salesforce that allow you to create custom data sets that can be accessed across your organization.

45. Explain the difference between Trigger.new and Trigger.newMap.

`Trigger.new` is a list of new versions of sObjects, while `Trigger.newMap` is a map of IDs to new versions of sObjects. `Trigger.newMap` is useful for efficiently finding new records based on their IDs.

46. How can you work with Maps and Sets in Apex?

Maps and Sets are collections in Apex. Maps allow you to store key-value pairs, while Sets store a unique collection of values.

47. What is the @TestVisible annotation used for?

The `@TestVisible` annotation allows methods or variables to be accessed by test methods within a separate class.

48. Explain the difference between a trigger and a process builder.

Triggers are blocks of code that automatically execute in response to specific events in Salesforce. Process Builder is a point-and-click tool for automating business processes using a graphical interface.

  • How can you work with JSON in Apex?

Apex provides the `JSON` class to serialize and deserialize JSON data. You can convert between Apex objects and JSON strings.

50. What is a Test Factory in Apex?

A Test Factory is a design pattern that helps you create test data efficiently and consistently for your unit tests. It simplifies the process of setting up test scenarios.

1. What is Async Apex in Salesforce?

Async Apex refers to the ability to execute Apex code asynchronously, which means it runs in the background without blocking the main execution thread. This is useful for handling long-running processes and tasks.

2. What are the different types of Async Apex in Salesforce?

There are three main types of Async Apex in Salesforce:

Future Methods: Annotating a method with `@future` allows it to be executed asynchronously.

Queueable Apex: You can create and enqueue a Queueable Apex class for execution.

Batch Apex: Batch Apex allows you to process large volumes of data in small, manageable chunks.

3. When would you use a Future Method in Salesforce?

You would use a Future Method when you need to execute a method asynchronously, such as making callouts, sending emails, or performing long-running operations without affecting the main transaction.

4. How do you invoke a Future Method in Salesforce?

You can invoke a Future Method by annotating a method with `@future` and then calling it like any other method. For example:

@future
     public static void myFutureMethod() {
         // Code to be executed asynchronously
     }

     // To invoke the method
     MyClass.myFutureMethod();
     
  • What is Queueable Apex, and why is it useful?

Queueable Apex is a way to perform asynchronous processing in a more controlled and organized manner. It allows you to add jobs to a queue and execute them in the order they are added, ensuring that they run sequentially.

6. What are some use cases for Queueable Apex?

Queueable Apex is suitable for various use cases, including complex data processing, long-running tasks, and handling multiple tasks in a specific order, such as data synchronization or batch operations.

7. How does error handling work in Queueable Apex?

If an exception occurs in a Queueable Apex job, Salesforce provides error information in the AsyncApexJob record associated with the job. You can use this information to troubleshoot and monitor job failures.

8. What are the key components of a Batch Apex class?

A Batch Apex class typically consists of three key components:

     `start`: This method identifies the initial set of records to be processed.

     `execute`: This method processes the records in small batches.

     `finish`: This method is called when all records have been processed.

9. How do you schedule a Batch Apex job to run asynchronously?

You can schedule a Batch Apex job to run asynchronously using the Salesforce user interface, the Developer Console, or programmatically by invoking the `Database.executeBatch` method.

10. What is the difference between Future Methods and Queueable Apex?

The main differences are:

– Future Methods are suitable for simple asynchronous tasks, while Queueable Apex provides more control and flexibility for complex processing.

– Future Methods execute independently, while Queueable Apex jobs can be queued and executed sequentially.

 – Future Methods have a limit of 50 method calls per transaction, whereas Queueable Apex allows more complex chaining of jobs.

1. What is scheduling in Salesforce?

Scheduling in Salesforce refers to the ability to automate the execution of certain processes, such as Apex jobs, reports, and dashboards, at specific times or on a recurring basis.

  • What is the Scheduler in Salesforce, and where can you find it?

The Scheduler in Salesforce is a feature that allows you to set up and manage scheduled jobs. You can find it in the Setup menu under “Apex Jobs” or “Scheduled Jobs,” depending on the specific type of job you want to schedule.

3. What types of jobs can you schedule using the Salesforce Scheduler?

You can schedule various types of jobs in Salesforce, including:

 Apex Jobs: Schedule the execution of Apex classes, such as batch jobs, future methods, and Queueable Apex.

Reports: Schedule the generation and distribution of reports.

Dashboards: Schedule the refresh and delivery of dashboards.

4. How do you schedule an Apex job in Salesforce?

To schedule an Apex job in Salesforce, you can use the `System.schedule` method, which allows you to specify the Apex class or job name, the time at which it should run, and optional recurrence settings.

5. What is the difference between a one-time scheduled job and a recurring scheduled job?

A one-time scheduled job runs once at the specified time, while a recurring scheduled job repeats at regular intervals according to the recurrence settings, such as daily, weekly, or monthly.

6. Can you schedule the execution of a custom Apex class, and if so, how?

Yes, you can schedule the execution of a custom Apex class by implementing the `Schedulable` interface and using the `System.schedule` method to specify when and how often the job should run.

7. What is the Cron expression, and how is it used in scheduling?

A Cron expression is a string representation of a schedule that specifies the timing of recurring jobs. It consists of fields for minutes, hours, days, months, and days of the week. Cron expressions are used to define the recurrence pattern of scheduled jobs.

8. How can you monitor the execution and status of scheduled jobs in Salesforce?

You can monitor the execution and status of scheduled jobs by navigating to “Apex Jobs” or “Scheduled Jobs” in the Salesforce Setup menu. You can view details such as job name, status, execution time, and any errors encountered.

9. What are some common use cases for scheduling in Salesforce?

Common use cases for scheduling in Salesforce include:

     – Running nightly data maintenance tasks.

     – Sending automated email reports to users.

     – Refreshing dashboards and data at specific intervals.

     – Automating data synchronization with external systems.

10. Can you cancel a scheduled job in Salesforce, and if so, how?

Yes, you can cancel a scheduled job in Salesforce by navigating to “Apex Jobs” or “Scheduled Jobs” in the Setup menu, finding the job you want to cancel, and clicking the “Abort” or “Delete” option, depending on the job’s status.

Proficient in Salesforce Health Cloud, a specialized customer relationship management (CRM) platform tailored for healthcare organizations.

Hits: 0

Share Post