Top Salesforce Apex Interview Questions and Answers
Salesforce provides many ways to automate the business process to fulfil our requirements. It has many standard automation tools such as workflows, process Builders, approval process etc. Organizations may have very complex business functionality which cannot be fulfilled by the standard automation tools. To achieve complex functionalities, Salesforce provides a programming language called APEX for developers to build applications. You can create web services, email services, and perform complex validation over multiple objects etc. using Apex language.
Good understanding in Apex has end up a large necessity for a number of job profiles in Salesforce. Most of the companies look for your capability in handling this remaining Feature of Salesforce. Since it's far in a lot demand there are many activity openings for the role of an Apex Salesforce Developer.
We are prepared for the individual problems who are looking forward to attending the Apex interview any time soon a very exhaustive list. The most popular interview questions and answers are given here in this blog will definitely help you in the right way. Here, we have included top Frequently asked questions along with their answers appropriate questions to help new talent in the field and experienced people.
If you are a person who has applied for a job somewhere and APEX developer you expect the interview to be scheduled soon, then you should take a brief look at this blog. In this blog, LearnFrenzy team has compiled some of the most frequently asked questions likely to show related to Salesforce Apex interviewed people.
1. What is Apex?
It is the in-house technology of salesforce.com. As per the official definition, Apex is a strongly typed, object-oriented programming language that allows developers to execute the flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API.
It has a Java-like syntax and acts like database stored procedures. It enables the developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages.
Features of Apex as a Language
Let us now discuss the features of Apex as a Language :
• Apex is a procedural scripting language in discrete and executed by the Force.com platform.
• It runs natively on the Salesforce servers, making it more powerful and faster than non-server code, such as JavaScript/AJAX.
• It uses syntax that looks like Java.
• Apex can written in triggers that act like database stored procedures.
• Apex allows developers to attach business logic to the record save process.
• It has built-in support for unit test creation and execution.
Apex provides built-in support for common Force.com platform idioms, including:
• Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in DmlException handling?.
• Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records.
- Looping that allows for bulk processing of multiple records at a time.
- Locking syntax that prevents record update conflicts.
- Custom public Force.com API calls that can be built from stored Apex methods.
- Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex.
MIND IT !
Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com
2. When Should Developer Choose Apex?
Apex should be used when we are not able to implement the complex business functionality using the pre-built and existing out of the box functionalities. Below are the cases where we need to use apex over Salesforce configuration.
Apex Applications
We can use Apex when we want to -
• Create Web services with integrating other systems.
• Create email services for email blast or email setup.
• Perform complex validation over multiple objects at the same time and also custom validation implementation.
• Create complex business processes that are not supported by existing workflow functionality or flows.
• Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object) like using the Database methods for updating the records.
• Perform some logic when a record is modified or modify the related object's record when there is some event which has caused the trigger to fire.
3. What is Apex Scheduler?
Apex scheduler is used to invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
The Schedulable interface contains one method that must be implemented, execute.
global void execute(SchedulableContext sc){}
The implemented method must be declared as global or public.
The following example implements the Schedulable interface for a class called mergeNumbers:
global class scheduledMerge implements Schedulable{ global void execute(SchedulableContext SC) { mergeNumbers M = new mergeNumbers(); } }
The following example uses the System.Schedule method to implement the above class.
scheduledMerge m = new scheduledMerge(); String sch = '20 30 8 10 2 ?'; system.schedule('Merge Job', sch, m);
You can also use the Schedulable interface with batch Apex classes. The following example implements the Schedulable interface for a batch Apex class called batchable:
global class scheduledBatchable implements Schedulable{ global void execute(SchedulableContext sc) { batchable b = new batchable(); database.executebatch(b); } }
Use the SchedulableContext object to keep track of the scheduled job once it's scheduled. The SchedulableContext method getTriggerID returns the ID of the CronTrigger object associated with this scheduled job as a string. Use this method to track the progress of the scheduled job.
To stop execution of a job that was scheduled, use the System.abortJob method with the ID returned by the.getTriggerID method.
4. Write a syntax and structure of scheduler class?
Sample class
global class ScheduleDemo implements Schedulable{ global void execute(SchedulableContext sc){ BatchClass b = new BatchClass(); database.executeBatch(b); } }
5. Give an example of Implicit and Explicit Invocation of apex?
• Implicit -> Triggers
• Explicit -> JavaScript Remoting
6. What is Scheduler class in Apex?
The Apex class which is programmed to run at pre defined interval.
Class must implement schedulable interface and it contains method named execute().
There are two ways to invoke scheduler:
1. Using UI
2. Using System.schedule (Schedule method of System class)
The classes which implements interface schedulable get the button texted with “Schedule”, when user clicks on that button; new interface opens to schedule the classes which implements that interface.
To see what happened to scheduled job, go to “Monitoring | Scheduled jobs “
Example of scheduling:
scheduledMerge m = new scheduledMerge(); String sch = '20 30 8 10 2 ?'; system.schedule('Merge Job', sch, m);
Here:
20 represents seconds
30 represents minutes
8 represents hour of the day
10 represents 10th day of month
2 represents month of the year
? represents day of the month
7. Write an apex code to send a email?
Sample code snippet to send an email using apex code
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[]{‘admin@learnfrenzy.com’}; mail.setToAddress(toAddresses); mail.setSubject(‘Sample Mail Subject’); mail.setPlainTextBody(‘Welcome to LearnFrenzy’); Messaging.sendEmail(new Messaging.SingleEmailMessage[]{mail});
8. What are the aggregate functions supported by salesforce SOQL?
Following aggregate functions are supported by salesforce SOQL
1. SUM()
2. MIN()
3. MAX()
4. COUNT()
5. AVG()
6. COUNT_DISTINCT()
9. Write a sample aggregate query or explain how to write a aggregate queries?
The return types of Aggregate functions are always an array of AggregateResult.
Sample Code
AggregateResult[] ar = [select AVG(Amount) aver from Opportunity]; Object avgAmt = ar[0].get(‘aver’);
10. Write a code to find the average Amount for all your opportunities by campaign?
AggregateResult[] arList = [select CampaignId, AVG(amount) from Opportunity group by CampaignId]; for(AggregateResult ar : arList){ System.debug(‘CampaignId ’ + ar.get(‘CampaignId’)); System.debug(‘Average Amount’ + ar.get(‘expr0’)); }
11. What are email services in salesforce and explain how we can use them in code?
Email services are automated processes that use apex class to process the contents, headers and attachment of an inbound email.
Sample code
Use Case: create a contact record if the inbound email subject is Create Contact and body contains contact name
global CreateContactFromEmail implements Messaging.InboundEmailHandler{ global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelop envelop){ Messaging.InboundEmailResult res = new Messaging.InboundEmailResult(); String strToCompare = ‘Create Contact’; If(email.subject.equalsIgnoreCase(strToCompare)){ Contact c = new Contact(); c.LastName = email.plainTextBody(); insert c; //save text attachments for(Messaging.InboundEmail.TextAttachment att : email.textAttachments){ Attachment a = new Attachment(); a.Name = att.fileName; a.Body = att.Blob.valueOf(att.Body); a.ParentId = c.Id; insert attachment; } //save binary attachments for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) { Attachment attachment = new Attachment(); attachment.Name = bAttachment.fileName; attachment.Body = bAttachment.body; attachment.ParentId = c.Id; insert attachment; } } res.Success = true; return res; } }
12. What is the row limit for apex:dataTable and apex:pageBlockTable?
The data set for both apex:dataTable
and apex:pageBlockTable
can have up to 1000 items.
13. What is the difference between apex:pageMessages, apex:pageMessage, apex:Message and apex:Messages?
apex:PageMessages:
This component displays all messages that were generated for all components on the current page, presented using the salesforce styling. This will display both salesforce generated messages as well as custom messages added to the ApexPages class.
apex:PageMessage:
Apex:PageMessage is a component that adds single message on the page. This is used to display custom message using the salesforce formatting.
apex:Message:
apex:Message is used to display an error on only a specific field. It is used to allow developers to place field specific errors in specific location.
apex:Messages:
apex:Messages is similar to apex:Message but it displays all errors
14. How can we hard delete a record using a Apex class/by code?
ALL ROWS key word can be used to get all the records including records in the recycle bin.
Below is the sample code to delete contact records from recycle bin
List dContactList=[Select ID From Contact Where IsDeleted = true limit 199 ALL ROWS]; Database.emptyRecycleBin( dContactList );
15. Write a syntax and structure of batch class?
When we want to deal with large number of records we go for batch apex. The code inside batch class runs asynchronously i.e in future context. The governor limit are also more as compared to synchronous code.
When we use batch apex we implements Database.batchable() interface
1. start
2. execute
3. Finish
Start method and finish method are called only once inside batch class.
• Start method collects the data for processing.
• Execute method performs operations.
• Finish method generally used for sending emails or calling another batch class when the current batch is completed.
Syntax :
global class batch implements Database.Batchable < sObject > { global (Database.QueryLocator or Iterable<sObject>) start(Database.BatchableContext bc) { //query on object; //return Database.getQueryLocator(query); } global void execute(Database.batchableContext bc, List < SObject > scope) { //some processing. } global void finish(Database.BatchableContext bc) { //job such as sending email or calling another batch class } }
Sample class :
global Class BatchDemo implements Database.Batchable{ global Database.QueryLocator start(Database.BatchableContext bc){ return Database.getQueryLocator(query); } global void execute(Database.BachableContext bc, List scope){ } global void finish(Database.BachableContext bc){ } }
Below code will call the batch class
BatchDemo bd = new BatchDemo(); database.executebatch(bd);
16. What is batch apex?
Batch Apex is asynchronous execution of Apex code, specially designed for processing the large number of records and has greater flexibility in governor limits than the synchronous code.
When to use Batch Apex?
• When you want to process large number of records on daily basis or even on specific time of interval then you can go for Batch Apex.
• Also, when you want an operation to be asynchronous then you can implement the Batch Apex. Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex. Batch Apex operates over small batches of records, covering your entire record set and breaking the processing down to manageable chunks of data.
Using Batch Apex
When we are using the Batch Apex, we must implement the Salesforce-provided interface Database.Batchable, and then invoke the class programmatically.
You can monitor the class by following these steps -
To monitor or stop the execution of the batch Apex Batch job, go to Setup -> Monitoring -> Apex Jobs or Jobs -> Apex Jobs.
Database.Batchable interface has the following three methods that need to be implemented ?
• Start
• Execute
• Finish
Let us now understand each method in detail.
Start
The Start method is one of the three methods of the Database.Batchable
interface.
Syntax
global void start(Database.BatchableContext BC, list) {}
This method will be called at the starting of the Batch Job and collects the data on which the Batch job will be operating.
Consider the following points to understand the method ?
• Use the
Database.QueryLocator
object when you are using a simple query to generate the scope of objects used in the batch job. In this case, the SOQL data row limit will be bypassed.• Use the iterable object when you have complex criteria to process the
records. Database.QueryLocator
determines the scope of records which should be processed.
Execute
Let us now understand the Execute method of the Database.Batchable
interface.
Syntax
global void execute(Database.BatchableContext BC, list) {}
where, listsobject
is returned by the Database.QueryLocator method
.
This method gets called after the Start method and does all the processing required for Batch Job.
Finish
We will now discuss the Finish method of the Database.Batchable
interface.
Syntax
global void finish(Database.BatchableContext BC) {}
This method gets called at the end and you can do some finishing activities like sending an email with information about the batch job records processed and status.
Batch Apex Example
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
We have to create a global apex class which extends Database.Batchable
Interface because of which the salesforce compiler will know, this class incorporates batch jobs.
Below is a sample class which is designed to delete all the records of Account object (Lets say your organization contains more than 50 thousand records and you want to mass delete all of them).
Examples:-
global class deleteAccounts implements Database.Batchable { global final String Query; global deleteAccounts(String q) { Query=q; } global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC,List scope) { List lstAccount = new list(); for(Sobject s : scope) { Account a = (Account)s; lstAccount.add(a); } Delete lstAccount; } global void finish(Database.BatchableContext BC) { //Send an email to the User after your batch completes Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {‘admin@learnfrenzy.com’}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done‘); mail.setPlainTextBody('The batch Apex job processed '); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
//This is how the batch class is called.
id batchinstanceid = database.executeBatch(new deleteAccounts(‘select Id from Account’));
17. What are web service callouts?
Apex Code supports the ability to expose Apex methods as a Web service. Apex also supports the ability to invoke external web services and this will refer to as 'Callouts.' The former is involved in creating a web service that a client can invoke, while the latter is invoking an external web service.
18. What are wrapper classes?
A wrapper or container class is a class, data structure, or an abstract data type whose instances are a collections of other objects.It is a custom object defined by Salesforce developer where he defines the properties of the wrapper class.
(4) Comments
Fantastic work!
clear explanation thank you
Hi Sameer , Great Explanation !! Can you please create a blog for Wrapper Classes. Thanks!!
In Salesforce, what are the key differences between using standard automation tools like workflows and process builders versus developing custom functionality with Apex? Can you provide examples of scenarios where it's more advantageous to use Apex for complex business processes?