0% found this document useful (0 votes)
109 views27 pages

Interview Questions Customization Coding Prafulla

An interface is a collection of unimplemented methods that specify signatures and types for methods. Apex can be used to create email services, web services, complex validations and processes not supported by workflows. Apex is a strongly typed programming language that allows executing flows and transaction control statements and adding business logic to system events. Apex classes can be called from other classes, the developer console, JavaScript links, home page components, triggers, and Visualforce pages. Wrapper classes are container classes that group related data and are used to display related records from multiple objects in Visualforce pages. Triggers execute before or after database events like insert, update, delete.

Uploaded by

Nikita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views27 pages

Interview Questions Customization Coding Prafulla

An interface is a collection of unimplemented methods that specify signatures and types for methods. Apex can be used to create email services, web services, complex validations and processes not supported by workflows. Apex is a strongly typed programming language that allows executing flows and transaction control statements and adding business logic to system events. Apex classes can be called from other classes, the developer console, JavaScript links, home page components, triggers, and Visualforce pages. Wrapper classes are container classes that group related data and are used to display related records from multiple objects in Visualforce pages. Triggers execute before or after database events like insert, update, delete.

Uploaded by

Nikita
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Q. What is Apex Interface?

Ans: Interface is a collection of unimplemented methods. This will specify the signature of the method,
types of inputs that we pass the method specify what type is given as an output.
Note: Generally the interface methods we give it as global.

Q. Where can I use Apex?


Ans: We can use Apex in the following ways
 To create Email services
 Create web services
 Perform complex validation over multiple objects
 To create complex business processes those are not supported by a workflow.
 Create custom transaction logic
 Attach custom logic to another operation

Q. What is Apex in Salesforce?


Ans: Apex is a strongly typed object-oriented programming language. It allows the developer to execute
flows and transaction control statements. Apex enables developers to add business logic to most system
events like button clicks related record updates and Visualforce pages.

Q. What are the ways to call the Apex class?


Ans: Below mentioned are the ways in Salesforce to call Apex class.
 From another class
 From developer console
 From JavaScript links
 From home page components
 By using trigger
 From Visualforce page

Q. What are Wrapper Classes in Salesforce? Give an example where you can use wrapper class!
A wrapper class in Salesforce is a Container Class which contains Objects, Collection of Objects,
variables, Collection of other classes as its member. We can also say that a wrapper class is a custom
object that Programmer defines to achieve the business need and defines the properties inside the
class.

Example: – We can use the Wrapper class in the following scenarios


a) In the Visualforce community boards, one of the most commonly asked questions is, “How can I
display a table of records with a checkbox and then process only the records that are selected?”.

Wrapper Class
b) OR we can use Wrapper class when we want to show the list of data in VF page or in any other classes
of the many objects that are not related to each other.

Q.What is Apex Email Service?


Ans: Email services are an automated process that uses Apex classes to process the contents, Headers,
Attachments of Inbound Email
Note:
-Visualforce email templates cannot be used for mass emails.
-We can associate each email service with one or more Salesforce generated email addresses to which
the users can send messages for processing.

Q. Explain about Apex Programming Language?


Ans:
-Integrated: It provides built-in support for DML Calls
-Inline Salesforce Object Query Language
-Easy to Use
-Easy to Test
-Version
-Multi-Tenant Aware Application

Q.What is Map Class in Apex Salesforce?


Ans:
Map Class Contains methods for the Map collection type.
A Map is a collection of key values pairs where each unique keymap to a single value.
Map keys and values can be any data type primitive types, collections, objects, user’s defined types, and
built-in Apex types.
For Example, the following table represents a map of countries and currencies
Country(Key) ‘United States’ ‘Japan’ France’ ‘England’ ‘India’
Currency (Value) ‘Dollar’ ‘Yen’ ‘Euro’ ‘Pound’ ‘Rupee’

Q. What is Trigger in Salesforce?


Ans: trigger is defined as an Apex code that executes before or after the following functions such as
insert, update, delete, etc. trigger enables to perform custom actions before and after modifications to
the records of Salesforce.
Following are the events on which trigger fires:
 Before insert
 Before update
 Before delete
 After insert
 After update
 After delete
 After undelete

Q. Broadly classify the Trigger?


Triggers can be broadly classified as before or after Trigger.
Before triggers are used to perform a task before a record is inserted or updated or deleted.
After triggers are used if we want to use the information set by Salesforce system and to make changes
in the other records

Q. What are the considerations while implementing the Triggers?


Consider the following before implementing the triggers.
 Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)
 Field history is updated after the trigger has successfully finished processing data.
 Any callout should be asynchronous so that trigger does not have to wait for the response.
 A trigger cannot have a static keyword in its code.
 If a trigger completes successfully the changes are committed to the database and if it fails the
transaction is rolled back.

Q.What is the Bulkification best practice?


Ans: We must avoid using index values like Trigger.New[0] as we never know how many records we get
in Trigger.New at runtime.
We need to use for each loop whether we have 1 record or many.
We must not use SOQL inside for loop.
We must not use SOSL inside for loop.
We must not use DML inside for loop.
We need to store data in collections, so our code will work for single as well as multiple records.

Q. Write the syntax of Apex Trigger?


Trigger TName On ObjName(name the events){
……. Apex code here ……..
}

What is a Time Trigger?


Ans: Computer system executes one or more tasks according to the set of rules and scheduled tasks.

What is the difference between trigger and workflow?


Ans: Workflow:
 Workflow is an automated process that fired an action based on Evaluation criteria and rule
criteria.
 Coding is not required.
 We can access a workflow across the object.
 We cannot perform DML operation on workflow
 We cannot query from database
Trigger:
 A trigger is a piece of code that executes before or after a record is inserted or updated.
 Coding is required.
 We can access the trigger across the object and related to that objects
 We can use 20 DML operations in one trigger.
 We can use 20 SOQL from the database in one trigger.

Q. What is difference overloading and overriding?


When two or more methods in the same class have the same name but different parameters, it's
called Overloading. When the method signature (name and parameters) are the same in the superclass
and the child class, it's called Overriding

Q. When to use Salesforce triggers


Ans: We should use triggers to perform tasks that can’t be done by using the point-and-click tools in the
Salesforce UI. For example, if validating a field value or updating a field on a record, use validation rules
and workflow rules instead.

Q.Trigger events in Salesforce?


A trigger is a set of statement which can be executed on the following events. In above trigger events
one or more of below events can be used with comma-separated.
Here is a list of trigger events in Salesforce
 before insert
 before update
 before delete
 after insert
 after update
 after delete
 after undelete

Q. What are the best practices for Triggers?


• Follow proper naming conventions to make your code more logical and readable.
• One Trigger per object: so you dont have to think about the order of execution as there are no control
over which trigger would be executed first
• Use trigger context-variables to identify specific event and performs tasks accordingly.
• Context-Specific Handler Methods: Using specific methods in your trigger-handler-class to keep your
code clean and scalable.
• Apex code must provide exception handling.
• When query large data set use an SOQL FOR loop.
• Don't use SOSL and SOQL inside for loop.
• Avoid Hard Coding IDs
• Use a framework: A framework! Why? It will make your code conform to the best practices, better
testing, scalability and cleaner.
• Keep the Salesforce order-of-execution of events in mind (they will come in handy).
• Understand when to use before-trigger and when to user after-trigger.
• Write trigger logic to support bulk operations.
• Triggers can't contain test methods. So, its unit tests must be saved in a separate file.
• Logic-less Triggers: use Helper class to handle logic.
• Code coverage: 100% (min 1%)
• Handle Recursion: to avoid the recursion on a trigger, make sure your trigger is getting executed only
one time. You may encounter the error: 'Maximum trigger depth exceeded', if recursion is not handled
well.

Q. What is difference between WhoId and WhatId?


 WhoID in Salesforce refers to people things. So that would be typically a Lead ID or a Contact ID.
The WhoId represents a human such as a lead or a contact. WhoIds are polymorphic. Polymorphic
means a WhoId is equivalent to a contact’s ID or a lead’s ID. The label is Name.
 WhatID in Salesforce refers to object type things. That would typically be an Account ID or an
Opportunity ID. The WhatID represents nonhuman objects such as accounts, opportunities, campaigns,
cases, or custom objects. WhatIds are polymorphic. Polymorphic means a WhatId is equivalent to the ID
of a related object. The label is Related To.

Q. What are trigger context variables in Salesforce?


All triggers define implicit variables that allow developers to access run-time context. These variables
are contained in the System.Trigger class.
1. Trigger.isExecuting: Returns true if the current context for the Apex code is a trigger, not a
Visualforce page, a Web service, or an execute anonymous() API call.
2. Trigger.isInsert: Returns true if this trigger was fired due to an insert operation, from the
Salesforce user interface, Apex, or the API.
3. Trigger.isUpdate: Returns true if this trigger was fired due to an update operation, from the
Salesforce user interface, Apex, or the API.
4. Trigger.isDelete: Returns true if this trigger was fired due to a delete operation, from the
Salesforce user interface, Apex, or the API.
5. Trigger.isBefore: Returns true if this trigger was fired before any record was saved.
6. Trigger.isAfter: Returns true if this trigger was fired after all records were saved.
7. Trigger.isUndelete: Returns true if this trigger was fired after a record is recovered from the
Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
8. Trigger.new: Returns a list of the new versions of the sObject records. This sObject list is only
available in insert, update, and undelete triggers, and the records can only be modified in before
triggers.
9. Trigger.newMap: A map of IDs to the new versions of the sObject records. This map is only
available in before update, after insert, after update, and after undelete triggers.
10. Trigger.old : Returns a list of the old versions of the sObject records. This sObject list is only
available in update and delete triggers.
11. Trigger.oldMap: A map of IDs to the old versions of the sObject records. This map is only
available in update and delete triggers.
12. Trigger.size: The total number of records in a trigger invocation, both old and new.

Q. What is the difference between Trigger.new and Trigger.old and Trigger.newmap and
Trigger.oldmap ?
Trigger.new returns new records and Trigger.old return data before updates were done.
Trigger.newmap returns new records with id's and Trigger.oldmap return data before updates were
done with id's.

Q.How is Trigger.New Different from Trigger.newMap?


Trigger.New variable returns the list of sObject which has invoked the trigger and Trigger.New Map
returns the map of ID’s with the newly entered records. NewMap is only available in after insert, before
and after the update and after undelete.

Q.Can a trigger call a batch class?


Yes, we can call a batch class in the trigger as we do in the normal apex code.

Q. What do you mean by the bulkifying trigger?


A trigger that can handle both single record and thousands of record. It is capable of handling mass
action.

Q. Define Recursive Trigger and how to avoid it?


There is a possibility that the result of the trigger can end up calling the same trigger again and can run
in a loop, this is known as a recursive trigger. To avoid this scenario we should create a static variable
and check the value of this variable before we execute anything in the trigger.

Avoid recursive trigger in Salesforce using static variable


To avoid this kind of situation we can use public class static variable.

In RecursiveTriggerHandler class, we have a static variable which is set to true by default.

1 public class RecursiveTriggerHandler{


2 public static Boolean isFirstTime = true;
3 }

In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting
static variable to false when trigger runs for first time. So if trigger will try to run second time in same
request then it will not run.

1 trigger SampleTrigger on Contact (after update){


2
3 Set<String> accIdSet = new Set<String>();
4
5 if(RecursiveTriggerHandler.isFirstTime){
6 RecursiveTriggerHandler.isFirstTime = false;
7
8 for(Contact conObj : Trigger.New){
9 if(conObj.name != 'SFDC'){
10 accIdSet.add(conObj.accountId);
11 }
12 }
13
14 // Use accIdSet in some way
15 }
16 }

Q. How many trigger we should write on one object?


We should always follow the best practice and consider writing one trigger per object. If we have more
than one trigger per object on same event say before insert then we cannot guarantee the order of
execution.

Q. What is the difference between database.insert and insert?


Using insert if one record fails entire operation is stopped and none of the record is inserted into
database, whereas with database.insert partial insertion is supported.

Q. What Are The Types of SOQL Statements in Salesforce?


Ans: Salesforce Object Query Language is used to query that records from the database.com based on
the requirement.
There are 2 types of SOQL Statements:
Static SOQL
Dynamic SOQL

Static SOQL:
The Static SOQL Statement is written in [](Array Brackets)
These statements are similar to IINQ (Ion Integrated Query)
Example 1:
String search for =’Jones’;
Contact[] contacts=[select testfield__c, FirstName, LastName from Contact Where Last Name=:search
for];

Dynamic SOQL:
It is used to refer to the creation of a SOQL string at run time with Apex code.
Dynamic SOQL enables you to create a more flexible application.
To create a Dynamic SOQL query at run time use Database.Query() method, in one of the following
ways.
Return a single sObjects when the query returns a single record.
sObjects s = Database. Query(String_limit_l);
Return a list of sObjects when the query returns more than a single record.
Example 1:- Queries
String myTestString = ‘TestName’;
List List= Database.Query(SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString);

Example 2:- Queries


String resolvedfield L = myvariable.field__c;
List L = Database.Query(‘SELECT Id FROM myCustomObject__c WHERE field__c = ‘+resolvedfield_L);

Q. Difference between SOQL Vs SOSL in Salesforce?


SOQL- (Salesforce Object Query Language) SOSL (Salesforce Object Search Language)
Using SOQL we can Search only on one object one time. Using SOSL we can search on many objects at
one time.
We can query on all fields of any data type We can query only on fields whose data type is text,
phone, and Email.
We can use SOQL in the Triggers and the classes. We cannot use in Triggers but can in classes.
We can perform DML operation on SQL query results. We cannot perform DML operations on search
results.

Q. Is there any limit on number of triggers define on an object?


We can define as many triggers on an object as we want but it is recommended to have one trigger per
object because the order of execution of different trigger is not guaranteed and any trigger can fire first

Q. Difference between Validation Rules and Triggers?


Validation Rules:
Validation rules are used to confirm that the data entered into a record meet various data quality /
business rules before letting the user save it.
Validation rules are very easy to create and virtually anyone can learn how to create these.
Triggers:
Triggers are more complex and generally require some development skills.
Triggers can be used for various different things and can be executed at different times - e.g. when
initiating a new record, before saving it, when a record is deleted.

Q. What are limitations of Workflows overcome by Triggers in Salesforce?


• Workflows are not able to create or update a separate object.
• You can’t reference certain fields when using workflows.
• You will not have your workflow doing more than just field updates and emails.

Salesforce Apex Interview Questions


1. What is Apex?
2. Explain about Apex syntax?
3. Does Apex support DML operations?
4. Is Apex strongly typed language?
5. Does Apex supports unit tests?
6. When should developers choose Apex?
7. What are the different data types in Apex?
8. What are the common methods of data types in Apex?
9. What are the limitations of Apex?
10. Does Apex support switch statements?
11. What types of statements we can use in Apex?
12. What types of collection does Apex supports?
13. How can you declare List/Map/Set in Apex?
14. What are the different types of Apex code development tools?
15. What is Force.com Developer Console?

Related Salesforce Interview Questions


 Salesforce Developer Interview Questions
 Demandware – Salesforce Commerce Cloud Interview Questions

Salesforce Apex Interview Questions and Answers


1) What is Apex?
A) Apex is a proprietary language developed by Salesforce.com. According to official definitions, Apex is
a strongly typed, object-oriented programming language that allows developers to execute traffic and
transaction control statements on the Force.com platform server while calling the Force.com API.
2) Explain about Apex syntax?
A) It has a Java-like syntax and is like a database stored procedure. It enables developers to add business
logic to most system events, including button clicks, related record updates, and Visualforce pages.
3) Does Apex support DML operations?
A) Apex has built-in support for DML operations such as INSERT, UPDATE, DELETE, and DML exception
handling. It supports inline SOQL and SOSL query processing, returning a set of sObject records.
4) Is Apex strongly typed language?
A) Apex is a strongly typed language. It uses direct reference to architectural objects such as sObject,
and any invalid references that fail if they are deleted or if they are of the wrong data type will fail
quickly.
5) Does Apex supports unit tests?
A) Apex provides built-in support for unit test creation and execution, including test results indicating
how much code is covered, and which parts of the code can be more efficient.
6) When should developers choose Apex?
A) Apex should be used when we can’t use pre-built and existing out-of-the-box functionality to
implement complex business functions.
7) What are the different data types in Apex?
A) Different data types available in Apex are,
1. Basic data type (Integer/Boolean/String)
2. Boolean
3. Date/Datetime/Time
4. ID (18 bits and 15 bits, can be converted to and from String)
5. Integer/Long/Double/Decimal
6. String
7. Blob
8. Object
9. Enum (enumeration type)
10. sObjects ( sObjects/Account/Position_c, etc. )
11. Collection (list, set, map, etc.)
12. User-defined and system custom objects
13. Null

8) What are the common methods of data types in Apex?


A) Common methods of data types
 Date: addDays()/dayOfYear()/daysBetween()/month()/toStartOfMonth()/year()
 Datetime: addHours()/hourGmt()/minute()
 String:
compareTo()/contains()/equals()/indexOf()/length()/split()/substring()/toUpperCase()/toLowerCase()
 Enum: ordinal()View location
 sObject: addError(), parent object_r
 List (ordered): add()/remove()/clear()/clone()/deepClone()/get/set/isEmpty()/size()/sort()
 Set (unordered, not repeated):
add()/addAll()/clear()/clone()contains()/cnstainsAll()/isEmpty()/remove/removeAll()/retainAll()/size()
 Map(key-value):
clear()/clone()/deepClone()/constiansKey()/get/set/isEmpty()/keySet()/put/putAll/remove/size/values

9) What are the limitations of Apex?


A) Apex limitations
The Apex programming language is saved and runs in the cloud – the Force.com multi-tenant platform.
Apex is tailored to data access and data manipulation on the platform, allowing you to add custom
business logic to system events. While it provides many benefits for business process automation on the
platform, it is not a general-purpose programming language.

Therefore, Apex cannot be used for:


1. Render elements in the UI instead of error messages
2. Change standard features – Apex can only prevent features from happening or add other
features
3. Create a temporary file
4. Generating threads

10) Does Apex support switch statements?


A) Apex does not support switch statements.

11) What types of statements we can use in Apex?


A) Like java, Apex must end with a semicolon; it can be one of the following types:
 Assignment, such as assignment to a variable
 Condition (if-else)
 Loop: Do-While, While, For
 Data manipulation language (DML)
 Transaction control
 Method call
 Exception handling (try catch)
 Locking

12) What types of collection does Apex supports?


A) Apex has the following types of collections:
1. Lists (arrays)
2. Maps
3. Sets

13) How can you declare List/Map/Set in Apex?


A) Apex is similar to Java’s List/Map/Set declaration method, except that it allows direct assignment
when declaring:
 List<Integer> My_List = new List<Integer>(){1,2,3};
 Set<String> My_String = new Set<String>{‘a’, ‘b’, ‘c’};
 Map<Integer, String> My_Map = new Map<Integer, String>{1 => ‘a’, 2 => ‘b’, 3 => ‘c’};

14) What are the different types of Apex code development tools?
A) In all versions, we can use the following three tools to develop code:
 Force.com Developer Console
 Force.com IDE
 Code editor in the Salesforce UI

15) What is Force.com Developer Console?


A) The Developer Console is an integrated development environment with a set of tools for creating,
debugging, and testing applications in your Salesforce organization.

16) What is sObject in Apex?


A) This is a special data type in Salesforce. It is similar to a table in SQL and contains fields similar to
those in SQL. There are two types of sObjects: Standard and Custom.

17) Can you write simple example code for sObject in Apex?
A) Here is the sample code for sObject,
//Declaring an sObject variable of type Account
Account objAccount = new Account();
//Assignment of values to fields of sObjects
objAccount.Name = ‘ABC Customer’;
objAccount.Description = ‘Test Account’;
System.debug(‘objAccount variable value’+objAccount);
//Declaring an sObject for custom object APEX_Invoice_c
APEX_Customer_c objCustomer = new APEX_Customer_c();
//Assigning value to fields
objCustomer.APEX_Customer_Decscription_c = ‘Test Customer’;
System.debug(‘value objCustomer’+objCustomer);
18) What in Enum in Apex?
A) An enumeration is an abstract data type that stores a value of a finite set of specified identifiers. You
can define an enumeration using the keyword Enum. Enumerations can be used as any other data type
in Salesforce.

19) Can you write sample example code for enumeration in Apex?
A) Here is the sample example code for enum,
Assuming you want to declare the possible name of the compound, then you can do this:
//Declaring enum for Chemical Compounds
Public enum Compounds {HCL, H2SO4, NACL, HG}
Compounds objC = Compounds.HCL;
System.debug(‘objC value: ‘+objC);

Advanced Salesforce Interview Questions and Answers


20) Difference between database methods and DML statements?
A) Differences between database methods and dml statements,
DML statement: Some updates are not allowed. For example, if there are 20 records in the list, all
records will be updated or not updated.
Database method: Allow partial updates. You can specify the parameter to true or false in the Database
method, true to allow partial updates, false to not allow the same.
DML statement: You cannot get a list of success and failure records.
Database method: You can get a list of success and failure records, as we saw in the examples.
DML Statement Example: insert listName;
Database Method Example: Database.insert(listName, False), where false means partial updates are not
allowed.

21) What are SOSL and SOQL methods in Salesforce Apex?


SOSL:
Searching for text strings across entire objects and fields will be done using SOSL. This is the Salesforce
object search language. It has the ability to search for specific strings on multiple objects.
The SOSL statement evaluates a list of sObjects, each of which contains search results for a particular
sObject type. The result list is always returned in the same order as specified in the SOSL query.
SOQL:
This is almost the same as SOQL. You can use it to get only one object record from an object. You can
write a nested query and get the record from the parent or child object you want to query.

22) What is Apex Call?


A) The Apex call refers to the process of executing the Apex class. The Apex class can only be executed
when called by one of the following methods:
 Triggers and anonymous blocks
 The trigger is called for the specified event.
 Asynchronous Apex
 Schedule the Apex class to run at specified intervals or run a batch job.
 Web service class
 Apex Email Service Class
 Apex Web Services, which allows you to expose your methods through SOAP and REST web
services.
 Visualforce controller
 Apex email service to handle inbound email.
 Call Apex using JavaScript
 The Ajax toolkit is used to invoke the Web service methods implemented in Apex.

23) What are Apex Triggers?


A) Apex triggers are similar to stored procedures that are executed when a specific event occurs. It is
executed before and after the event is logged.
Syntax: Trigger triggerName on ObjectName ( trigger_events )
{ Trigger_code_block }

Batch Apex:
Q. What is Batch Apex in Salesforce?
Ans: Batch Apex allows you to define a single job that can be broken up into manageable chunks,
whereas every chunk can be processed separately. In the Batch Apex it will fetch all the records on
which you want to perform the field update and divide them into a list of 200 records and on every 200
records operation are performed separately.
This would help us to execute on more than 10,000 records as it won’t perform an operation on all the
records in a single transaction instead it dividing them into Number of subtasks where each subtask may
contain the records up to 4000.
Example:
If you need to make a field update of every record of account object in your organization, then we have
governing limits that would restrict us from achieving the above task.
Reason: In a single transaction we can process only 10,000 records. Now in the above case if we have
more than 10,000 records in the organization then we cannot perform this field update.

Q.What is Apex Scheduler?


Ans: It will invoke the Apex classes to run at a specific time.
Anybody who wants to schedule their class they have to implement the schedulable interface.
Schedule Interface: The class that implements this interface can be scheduled to run at different
intervals.

Q. Explain various methods of batch Apex class?


Ans: The Database Batchable contains three methods that must be implemented.
-Start method
-Execute method
-Finish method

24) What is Batch Apex?


A) Batch Apex is asynchronously executed Apex code designed to handle large numbers of records and
has more flexibility in terms of regulator limits than synchronous code.

25) When do you use batch processing of Apex?


A) When you want to process a large number of records every day, or at specific intervals, you can go to
Batch Apex.
Also, when you want an operation to be asynchronous, you can implement batch processing. Batch
Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be called
programmatically at runtime using Apex. Batch Apex operates on small batch records, overwriting the
entire recordset, and breaking the process down into manageable blocks of data.

1. How many active batches(running parallel) can be allowed at a time?


Salesforce by default allows 5 active batches running at a time and other batches will be in queue for
running

2. How can we schedule batch class to run in future only once from the specified minutes from current
time.
public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer
minutesFromNow)
or
public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer
minutesFromNow,Integer batchSize)

3.How to calculate the batch size if we are making any call out from the batch class execute method?
Basically in Salesforce we have limitation of 100 call outs for a transaction.When it comes to batch class
each execute method call will be considered as one transaction. So, in this case your batch size must be
calculated in such way
Batch size = (No of callouts allowed for single transaction /total number of call outs for each record) -
1;
Batch size = (100 /total number of call outs for each record) - 1;

4. How to stop all the running batches related to a particular batch classes before scheduling the same
batch class from the schedule class.
global class CaseCreationonSchedular implements Schedulable
{
global void execute(SchedulableContext SC)
{

for(AsyncApexJob ap: [SELECT Id, ApexClass.Name,createddate, JobType, Status,


JobItemsProcessed, MethodName, ParentJobId FROM AsyncApexJob Where ParentJobId!=Null AND
JobType IN('BatchApex','BatchApexWorker') And ApexClass.Name='YourBatchClassName' And Status
NOT IN('Completed','Aborted')])
{
System.abortJob(ap.ParentJobId);

}
YourBatchClassName cls = new YourBatchClassName();
DataBase.executeBatch(cls);
}
}

5.How can we schedule a batch class to run every 10 or 5 or 2 mins.


Salesforce haven't provided wild card entries (* every,- range,/,?) in place of minutes and seconds.So,if
you want schedule a class to run every 10 minutes you have to schedule same class 6 times (60min/6)
with diff batch name ,for 5 mins 12 times and for 2 mins 30 times..As the time interval keeps going down
schedule the same class goes up which is an irritating thing to monitor or even it's very hard to handle
these many jobs.

For this we can simply do this in the code so that at any given point of time you will have only schedule
job running for the same.

global class CaseCreationonSchedular implements Schedulable


{
public void execute(SchedulableContext scon)
{
System.abortJob(scon.getTriggerId()); // abort already running schedule job
Decimal nextInterval = System.Label.nextIntervalTime; // config to decide next interval 2,5 or 10
mins etc..
System.schedule('CaseCreationonBatch - '+String.valueOf(DateTime.now()), '0
'+DateTime.now().addMinutes(Integer.valueOf(nextInterval)).minute()+' */1 ? * *', this); //Schedule the
class to run with specified time

Database.executeBatch(new YourBatchClassName()); // Call you batch class

}
}

6.Why to use Batch class as we already having data loader to process the bulk data.
Agree with this point if and only if the data needs to be updated is static or predefined or which can be
done through excel.
We will choose batch class if we have to perform some custom calculations at run time or if you want to
run some complex logic which can't be driven by excel sheets in those cases we have to go with batch
classes.
Examples:
 Do some relationship quires to update the data.
 Make a call out to get the some information related to each record.

7.How many times the execute method will be executed to process the 1234 records.
It depends on your batch size what you have configured at the time of calling the batch class from
schedule class.
Execution method count = Total No Of Records/Batch Size (Any decimal ceil it to upper value)
 If you haven't set any batch size then - 1234/200 = 6.17 = 7 times execute method will be called

8.What is the maximum size of a batch that we can set up ?


2000
9.What is the minimum batch size we can set up is?
1
10.What is the default size of batch if we haven't configured at the time of execution?
200
11.What is Apex Flex Queue?
At a time Salesforce allows 5 batches to be running or to be in queued state. So, if you have consumed
all these 5 limits and if system has received one or more batch execution request all these waiting batch
will be stored in this Apex Flex Queue.

12. What is the maximum number of batch classes allowed in Apex Flex Queue for execution?
100

13. How can we do chaining of batch jobs?


we can do this by simply calling the chained batch/second batch class from the finish method of the first
batch class.
Why to call only from the finish method why not from execute? Because the execute method will gets
invoked multiple times based on the volume of the records and batch size. So, if your calling it from
executes method then the chaining class will get called multiple times which is not an suggested way of
doing.

……………………….
26) How do you debug the code in Apex?
A) In Apex, we have some tools for debugging. One of them is the system.debug() method, which prints
the value and output of the variable in the debug log.
There are two tools that you can debug:
 Developer console
 Debug log

27) What is Force.com Migration Tool?


A) This tool is used for script deployment. You must download the Force.com migration tool and then
you can perform a file-based deployment. You can download the Force.com migration tool and then
perform a script deployment.
28) What is SOQL loop?
A) This type of for loop is used when we don’t want to create a List and traverse the return recordset of
a SOQL query directly. We will delve deeper into SOQL queries in the next chapter. Now, just remember
that the list of records and fields it returns is given in the query.
Syntax:
for (variable : [soql_query]) { code_block }
or:
for (variable_list : [soql_query]) { code_block }
29) What is Blob in Apex?
A) Blob: Binary storage type generally used to receive uploaded attachment, documents, etc.
30) What is ID type in Salesforce Apex?
A) ID: This type is unique to Salesforce and is used to represent the 18-bit id identifier of salesforce’s
sObject.

Salesforce Apex Interview Questions and Answers For Experienced


31) How do you convert a string to an Integer type?
A) Convert a string to an Integer type, valueOf(), for example:
Integer.valueOf(’12’); //12;
Integer.valueOf(’12a’); //throw TypeException
32) How do you convert long type is converted to int method?
A) Long type is converted to int method, intValue(), for example:
Long curLong = 71;
Integer myInt = curLong.intValue(); //71
33) What does contain method do in Apex?
A) contains() to see if the string contains a method for a specified string.
E.g:
String str1 = ‘abc’;
String str2 = ‘a’;
str1.contains(str2); //true

34) Can you explain some string methods which were used in your projects?
A) I worked with various string methods in my previous projects, they are,
1) startsWith()- whether the string begins with a given string.
2) endsWith()- whether the string ends with a given string.
3) toUpperCase()- which is capitalized.
4) toLowerCase()- which is changed to lowercase.
5) length()- to find the length of the string.
6) replace()- replaces the string matching content.
7) split()- splits the string into a List collection according to the specified string.
8) trim()- remove the spaces before and after the string.
9) indexOf()- which gets the index of the first match of the string with the given string, and -1 if there is
no match.
10) lastIndexOf()- which gets the subscript of the last match of the string with the given string, and no.
11) substring()- intercepts the string between the given subscripts in the string.

35) Can you explain about few commonly used date type methods?
A) Date and DateTime methods are many, I will mention a few commonly used methods here,
1) newInstance(), create a Date.
E.g:
Date d = Date.newInstance(2019,1,15); //2019-1-15
2) day(), get the day of the date.
E.g:
Date d = Date.newInstance(2018,9,12);
d.day(); //12
3) month(), get the month in the date.
E.g:
Date d = Date.newInstance(2018,9,12);
d.month(); //9
4) year(), get the year in the date.
E.g:
Date d = Date.newInstance(2019,9,12);
d.year(); //2019
5) daysBetween(), get the number of days between the two dates.
E.g:
Date startDay = Date.newInstance(2018,9,12);
Date endDay =Date.newInstance(2018,10,2);
startDay.daysBetween(endDay); //20
6) addDays(), add the number of days.
E.g:
Date d = Date.newInstance(2018,9,12);
d.addDay(3); //2018-9-15
7) getTime(), which is the number of milliseconds elapsed from 1970-01-01 00:00:00 to the calculation
time.
E.g:
DateTime d = Date.newInstance(2018,9,12,8,0,0);
d.getTime(); //1473681600000

36) What are the characteristics of Apex?


A) Apex has the following characteristics
1) Integration
 Insert, update and delete, etc., are included in the DmlException, called in the DML language.
 The return is sObject type recode list, tandem Salesforce Object Query Language (SOQL) and
Salesforce Object Search Language (SOSL) query
 Multiple records can be processed simultaneously
 Encounter repeated data updates automatically avoid, and lock
 The saved Apex method can be rebuilt, and can call the generic Force.com API
 The referenced Apex custom object or custom project will be warned when it is edited or
deleted.
2) More convenient to use
Apex’s variables and syntax components, modules, conditional declarations, loop declarations,
representations of objects and arrays are all based on JAVA. Considering that Apex is easier to
understand when importing new features, the Force.com platform can run more efficiently and develop
Apex.
3) Data pointing
And developers in the database server in the same essentials conduct multiple transactions declared by
the database stored procedure, on the Force.com platform server, Apex multiple queries and DML
statements are designed to a session. As with other database stored procedures, Apex does not support
execution on the user interface.
4) Very clear
The object name and project name in Apex are directly referenced to the schema object and are
strongly typed languages. When this reference is not available when the reference is not found, a
compilation error will occur immediately. In order to prevent the referenced Apex code from being
deleted, all the standard items in the master data and the class associations are saved.
5) Autonomy
The Apex language is based on the implementation, control and control of the Force.com platform.
6) Multi-tenancy
Like other Force.com platforms, Apex is implemented in a rented environment. To accommodate this
environment, Apex’s real-time engine is designed to avoid code that interferes with each other, and the
shared code is not occupied by a single tenant. When the code that violates the rule fails to execute, an
error message that is easy to understand is displayed.
7) can be automatically upgraded
In Apex, the upgrade of other parts of the Force.com platform does not need to be directly described.
Because the compiled code is saved as master data in the platform, Apex has also been upgraded as part
of the release.
8) Easy to test
In Apex, how much is the code covered, is it more effective than a certain part of the code? They are all
expressed in the test results, etc., and can be tested and executed as a single unit. In Salesforce, all of
the individual tests were performed before the platform upgrade, and it was confirmed that all standard
Apex code was executed as expected.
9) Have version management
The version of the Apex code change can be saved in the Force.com API. According to this, to maintain
normal operation. Apex includes Performance Edition, Unlimited Edition, Developer Edition, Enterprise
Edition and Database.com.
37) What are the conditions for using Apex?
A) Salesforce is a combination of various functions that provide CRM (customer relation manage)
applications. Or, SalesForce is a custom application that integrates the corresponding organization.
However, organizations have parts that do not support their own complex business processes. In the
SalesForce platform, senior administrators and developers can package a variety of methods. Among
these methods are Apex, VisualForce, and Soap APIs.
1) Apex – Use Apex for the following occasions
 Web service
 Create a mail service
 Detect multiple complex objects
 Create complex business processes that are not supported in workflow
 Make a custom transaction (not just a single record, object, the logic of the transaction)
2) Visualforce
Visualforce uses a tag-based tagging language that allows developers to develop user interfaces while
developing efficient ones. With VisualForce, you can do the following
 Build other multiple steps such as weChat
 Develop custom controllers independently between applications
 Navigation patterns and inherent rule definitions for the most appropriate and effective
application interaction.
 For details, please refer to the book “VisualForce Handwriting” on the SalesForce website.
3) SOAP API
The need to manage only one record type at a time, managing transactions (savepoint settings and
rollback of changes, etc.) does not use the standard SOAP API call without adding functionality to the
composite application.
38) What are the functions of Apex?
A) Apex is compiled, saved and executed on the Force.com cloud platform. When the developer saves
the Apex code, the application server of the cloud platform translates the abstract command settings
into assembly code that can be recognized by the background according to the Apex real-time
translator, and then saves the commands as a metadata to the cloud platform.
The end user clicks the button and accesses the VisualForce screen to execute the Apex code. The
application server of the cloud platform obtains the compiled command from the metadata, passes it to
the cloud through the real-time program translator, and then returns the running result. The end user
does not have to care about the requirements of the cloud platform and the difference in program
execution time.
……………………………………………………………………………………………………………………………………………………………..
Errors in Salesforce:
1.Mixed DML Operation Error:
Reason: When you try to combine DML operations for both Setup and Non-Setup objects
in a same transaction (Where Setup objects such as Group, Group member, Queue SObject, User. Non-
Setup Objects such as Standard and Custom Objects).
Resolution: We can use @future annotation to do DML operation. It will split the transactions.
Another approach is to use same logic in a batch class to overcome.
2.Cpu time limit exceed:
Reason 1: Based on CPU usage, Salesforce has a timeout limit for each transaction.
Due to consumption of too much CPU time limit in a transaction, this error could occur.
Reason 2: If you use nested for-loop (for-loop inside another for-loop), then you must use Map(s) to
resolve the issue, as it is one of the common reasons for CPU Time Limit
For 
{ 
 for 
 { 
 } 
}
Counted: 
 All Apex Code.
 Workflow execution.
 Library functions exposed in Apex.
Not Counted: 
 Database Operations (DML)
 SOSL
 SOQL
 HTTP Callouts.
3.System.QueryException: Non-selective query against large object type:
Reason: If you query records on object that returns more than
200,000 records and without query filters, it’s possible that you’ll receive the error,
“System.QueryException: Non-selective query against large object type.” We’ll go over the a few
possible fixes.
Resolution: It’s best to try to have that field indexed by checking the “external ID” checkbox when
you create that field.  Also, as a best practice, always use WHERE clause in your SOQL
statements to read the records.
Example: [Select id, Name, Type from Account WHERE Type = “Prospect”];
Finally, filter out all null records in your Apex query.
4.Too many SOQL Queries:
Reason: We can run up to a total of 100 SOQL queries in a single transaction or context. All the SOQL
queries in triggers fired from one call or context will be counted against the limit of 100.  When the
number of SOQL queries exceed the limit in a single transaction, then this error is thrown by Salesforce.
Resolution: To fix this issue, you’ll need to change your code in such a way that the number of SOQL
fired is less than 100. If you need to change the context, then you can use @future annotation which will
run the code asynchronously. Here are some best practices that will stop the error messages.
Governor Limit:
1. Since Apex runs on a multi-tenant platform, the Apex runtime engine strictly enforces limits to ensure
code doesn’t monopolize shared resources. Learn about the Governor Limits
2. Avoid SOQL queries that are inside for loops.
3. Check out the Salesforce Developer Blog where you can find Best Practices for Triggers.
4. Review best practices for Trigger and Bulk requests on our Force.com Apex Code Developer’s Guide.
5. Be sure you’re following the key coding principals for Apex Code in our Developer’s Guide.
Important: Salesforce cannot disable the Governors Limit or raise it. Following the best practices above
should ensure that you don’t hit this limit in the future.
5.Non-recursive Parameterized interface method generating infinite recursion error: “Maximum stack
depth reached: 1001”:
Reason 1: Let’s say in ‘after update’ trigger, a Developer is performing update operation and this
leads to recursive call.
Resolution: We can create a class with a static Boolean variable with default value true. In the trigger,
before executing your code keep a check that the variable is true or not. After you check, make the
variable as false.
Example Code: 
Class:  

public class ContactTriggerHandler 

{ 

     public static Boolean isFirstTime = true; 

} 

Trigger: 

trigger ContactTriggers on Contact (after update) 

{ 

    Set<String> accIdSet = new Set<String>();  

    if(ContactTriggerHandler.isFirstTime) 

    { 

        ContactTriggerHandler.isFirstTime = false; 

         for(Contact conObj : Trigger.New) 

  { 

            if(conObj.name != 'Test')  

     { 

                accIdSet.add(conObj.accountId); 

            } 
         } 

   // any code here 

    } } 
6. Too many Query rows: 
Reason:  The exception is being thrown because the maximum number of rows we can return in SOQL
calls in Apex is 50000.
Resolution: Limit the query results by adding limit. If you want to insert additionally, you will need to
use Batch Apex in which the 50K limit counts per batch execution. This limit Counts for each
transaction and these limits are reset for each execution of a batch of records in the execute method.
7. Error: System.ListException: List index out of bounds: 0
Reason: Our Query has returned no records that match the criteria. If you then attempt to access an
element at row 0, this will throw an error as that row doesn’t exist.
Resolution: Initially Always Check whether the list has records or not.
Error Code:
List<custom obj__c> lrecords=[select Id,name from custom obj__c  ]; 

 lrecords[0].Fileld1__c=2; 
 lrecords[0].Fileld2__c=3; 
update lrecords; 

Modified Code: 

List<custom obj__c> lrecords=[select Id,name from custom obj__c  ]; 

If(lrecords.size()>0) 

{ 

 lrecords [0].Fileld1__c=2; 
 lrecords[0].Fileld2__c=3; 
update lrecords; 

} 
8. Error: Sobject row was retrieved via SOQL without querying the requested field:
Reason: This Error is caused by using the field that is not queried in the SOQL query.
Wrong Code:  
Code: Id ids = ‘0012800001EOUIl’; 

List<Contact> c =new list<Contact>([Select id from Contact WHERE id =” ids]); 

String Conname = c[0].Name; 

System.Debug(‘@@@@’+c[0].id); 

Resolution: We must add the field name in the query. 


Modified Code:  

Id ids = ‘0012800001EOUIl’; 

List<Contact> c =new list<Contact>([Select id,name from Contact WHERE id =” ids]); 

String Conname = c[0].Name; 

System.Debug(‘@@@@’+c[0].id); 
9. System.QueryException: List has no rows for assignment to SObject:
Reason: This error is caused when the query cannot get the results back.
Resolution:  
Id ids = null’; 

Contact c = [Select id,name from Contact WHERE id =” ids]; 

System.Debug(‘@@@@’+c.id); 

Modified Code: 

Id ids = ‘Null’; 

If(ids!=Null) 

{ 

Contact  c = [Select id,name from Contact WHERE id =” ids]; 

System.Debug(‘@@@@’+c.id); 

} 
10. System.AsyncException: Rate Limiting Exception: AsyncApexExecutions Limit exceeded:  
Reason: This error occurs when we are hitting an org-wide 24 hour rolling limit on asynchronous Apex.
The maximum number of asynchronous Apex method executions (batch Apex, future methods,
Queueable Apex, and scheduled Apex) per a 24-hour period: 250,000 or the number of user licenses in
your organization multiplied by 200– whichever is greater”.
11. System.AsyncException: Maximum callout depth has been reached: 
Reason: Queueable Apex Limits
The execution of a queued job counts against the shared limit for asynchronous Apex method
executions.
Resolution:
 You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
 No limit is enforced on the depth of chained jobs, which means that you can chain one job to
another job and repeat this process with each new child job to link it to a new child job. For Developer
Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you
can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent
queueable job.
 When chaining jobs, you can add only one job from an executing job with System.enqueueJob,
which means that only one child job can exist for each parent queueable job. Starting multiple child jobs
from the same queueable job isn’t supported.
12.System.DmlException: Insert failed. First exception on
row2; firsterrorINSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on
cross-reference id: []:
Reason: This error normally happens when a DML operation is performed with a wrong record Id.

13.System.NullPointer Exception: Attempt to Dereference a null object:


Reason: If we use the collections without initializing and if we use any methods of a null object or refer a
null variable, null pointer or object exception will occur.
Sample Code:
List<Contact> contactList; 
Contact contactIns = new Contact(); 
ContactIns.LastName = 'test'; 
ContactList.add(contactIns ); 

14.Error: Invalid Data.:  Apex trigger Acc caused an unexpected exception, contact your
administrator: Acc: execution of AfterInsert caused by: System.DmlException: Insert failed. First
exception on row 0 with id 0032800000vimdqAAA; first
error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]: Trigger.Acc: line 11,
column 1:
Reason: While inserting a record in Trigger. the dml should be outside the for loop.
Sample Code:
This is the wrong code:
trigger Acc on Account (after insert) { 
    List<Contact> ListCont =New List<Contact>(); 
   for(Account acnt : Trigger.New){ 
       for(integer i=0;i<3;i++){ 
           Contact Cont=new Contact(); 
           cont.Lastname=acnt.name+'ContApex1'; 
           cont.accountid=acnt.id; 
           ListCont.add(cont); 
           insert ListCont;     
 } } } 

15.Error: Record is Read only:


Reason: When you are doing an After trigger, Trigger.new is read only. If you want to make changes to
it, then it is best to do it in a Before trigger.
Also, your trigger is not bulkified. If more than one record is updated at a time, then only the first one
will be evaluated.
Wrong Code:
trigger sample on Account (after insert) { 

 for (Account sample: Trigger. New) {            

sample. Email =sample.Email__c; 
}}
Modified Code:
trigger sample on Account (after insert) { 

List<Account> Acclis = [SELECT Id,Name,Email,Email__C FROM Account WHERE Id IN:


Trigger.newMap.keySet()]; 

for (Account Acc: Acclist){ 

Acc.Email = Acc.Email__c; 

}Update Acclist;}

16.Required Field Missing:


Reason: In DML operation, we have missed the required field for the sObject.
Code: trigger Acc on Account (after insert) { 

    List<Contact> ListCont =New List<Contact>(); 

   for(Account acnt : Trigger.New) 

   { 

       for(integer i=0;i<3;i++) 

       { 

           Contact Cont=new Contact(); 

            

           cont.accountid=acnt.id; 

           ListCont.add(cont); 

              

       } 

   } 

        insert ListCont;     

Modified Code:
 trigger Acc on Account (after insert) { 
    List<Contact> ListCont =New List<Contact>(); 

   for(Account acnt : Trigger.New) 

   { 

       for(integer i=0;i<3;i++) 

       { 

           Contact Cont=new Contact(); 

           Cont.Lastname = acnt.Name+’Sample’;   //This is the required field in Contact 

           cont.accountid=acnt.id; 

           ListCont.add(cont); 

              

       } 

   } 

        insert ListCont;     

} 

17. Error: Compile Error: Invalid foreign key relationship: Account.Site at line 15 column 12:
Reason: While assigning a field value, the Syntax should
be SobjectName.FieldName or SObjectName.method()
Sample Code (Error) 

trigger sample on Account(before insert, before update){ 

 integer i = 0;  

Map<String, Account> accountMap = new Map<String, Account>{}; 

for (Account acct : System.Trigger.new) 

accountMap.put(acct.Name,acct); 

for (Account oldAccount: [SELECT Id, Name,Site FROM Account WHERE Name


IN:accountMap.KeySet()]){ 

Account newAccount = accountMap.get(oldAccount.Name); 
i = newAccount.Site.length; 

} 

} 

Modified Code: 

trigger sample on Account (before insert, before update){ 

 integer i = 0;  

 Map<String, Account> accountMap = new Map<String, Account>{}; 

for (Account acct : System.Trigger.new) 

accountMap.put(acct.Name,acct); 

for (Account oldAccount : [SELECT Id,Name,Site FROM Account WHERE NameIN :accountMap.KeySet()])


{ 

 Account newAccount = accountMap.get(oldAccount.Name); 

 i = newAccount.Site.length(); 

}} 

18.System.security. NoAccessException: Update access denied for RecordType controller action


methods may not execute:
Reason: This error means that the profile that executes the apex code has no permission to
create the sObject.
Resolution: Check whether do you have access to the apex code, or to modify your profile
– change the first line of apex code from “public with sharing…” to “public without sharing…”.
or
- Add create permission to your profile (setup / manage users / profiles / your profile / check create
checkbox in account object)

19. System.SObjectException: DML statement cannot operate on trigger. New or trigger. Old:


Trigger.extractnumericvalues:
Reason: We cannot perform DML operation in before insert/before update in same record. Also, refer
the Order of Execution.
Sample Code:
trigger extractnumericvalues on Account (before insert) {

list<account> acList = new list<account>();

Matcher matcher;
Pattern pat;

for(account acc : trigger. New)

if(acc.AccountNumber != null)

pat = Pattern.compile('[0-9]');

matcher = pat. matcher(acc. Account Number);

Boolean matches = matcher.find();

acc.Copy_Me__c = matcher.group();

acList.add(acc);

insert acList;// Error will flow here because we cannot do dml for the same record.

20.Error: Invalid Data Review all error messages below to correct your data.


Apex trigger trigger task caused an unexpected exception, contact your administrator: trigger task: data
changed by trigger for field Pick Val: bad value for restricted picklist field: Val10:
Reason: In trigger, when we try to insert new values into the picklist rather than using the existing values
in the picklist, this error will fire during insertion.
Resolution:
Solution 1:  To accept the new values apart from the existing picklist values: Goto View Fields–
>Corresponding Picklist–>Edit–>Picklist Options–>uncheck the “Restrict picklist to the values defined in
the value set”.
Solution 2: Adding a necessary picklist value to the existing picklist.

You might also like