Apex is an object-oriented programming language developed by salesforce.com that allows programmers to write code that can be accessed with other languages, such as JavaScript or Java. It supports most of the features of Java but adds specific security restrictions that allow access to data only through methods specified in classes, rather than directly accessing fields within instances of objects.
Apex is a platform for building large-scale applications, allowing users to build complex business systems over various platforms, including mobile devices and tablets. These applications are called Force Applications (FA). The system uses database records, called DataSets, to store information along with their relationships. This enables developers to work on a single set of data regardless of what device they use.
Apex has several components, from the high-level language apex itself down to each component’s subcomponents, such as VisualForce Pages, Lightning Components, Process Builder, Workflow Rules, etc.
Here we have covered 45+ Salesforce Apex interview questions and answers.
You can use this page to get a good start on preparing for your next interview at Salesforce. We have segregated our questions into different sections and are putting them together here so you can quickly find what you need without having to hunt around. You can also bookmark this site or add it to your favorites if you wish to refer back to this resource later.
Salesforce Apex Beginner Interview Questions
- What is Apex Interface?
It is an interface of methods that are not implemented. We will use this to specify the signature of a method, the types of inputs we pass to the method, and the type of output.
- In what situations can Apex be used?
The following are some ways we can use Apex
- To create Email Services
- To create Web Services
- To perform complex validation on multiple objects
- In order to create complex business processes that are not supported by a workflow.
- Customize the transaction logic
- Attach custom logic to another operation
- So, how does Apex work?
Apex programs are completely On-Demand on the Force.com Platform.
- The platform application server first compiles the code into an abstract set of instructions that Apex runtime interpreters can understand.
- Compilation metadata are then stored on the platform application server.
After the end-user triggers Apex by clicking a button or the VisualForce page, the application servers retrieve the compiled instructions from the metadata and send them to the runtime interpreter before returning the result.
- How does Apex work in Salesforce?
Apex is an object-oriented programming language with strong typing.
It allows developers to implement flows and transaction control statements.
Using Apex, developers can add business logic to most system events, such as button clicks related to record updates and VisualForce pages.
- How can Apex classes be called?
Below are the methods for calling Apex classes in Salesforce.
- By calling another class
- From the developer console
- From the JavaScript links
- From the home page components
- By using the trigger
- From the VisualForce page
- What are the various methods of the batch Apex class?
The batch apex class provides three methods to implement the database batchable interface:
- Start
- Finish
- Execute
Start: The start method is used at the beginning of the batch apex job. This is used for collecting the objects or records, as well as for passing them to the interface for processing. The object returned is a DatabaseQueryLocator object, which contains the objects or records sent to the job.
Finish: Call this method once batch processing has been completed. Using this method, we can send confirmation emails and perform post-processing operations.
Execute: For every batch of records that are sent to the method, we use this method. This method is used to process data. The method performs the following functions:
- Returns a list of sObject records
- Reference to the DatabaseBatcheable context.
- How does Apex Email Service work?
Apex classes are used to process Headers, Attachments, and Contents of Inbound Emails using Email Services.
Note:
- Visualforce email templates cannot be used to send mass emails.
- The users can send messages to one or more salesforce-generated email addresses associated with each email service.
- How does Apex syntax work?
There is a Java-like syntax and it’s like a database stored procedure. Developers can add business logic to most system events, including button clicks, record updates, and Visualforce pages.
- Are DML operations supported by Apex?
As part of Apex, you can perform operations such as INSERTs, UPDATS, DELETES, and handle DML exceptions. Inline SOQL and SOSL query processing is supported, returning a set of sObject records.
- How does the Apex language work?
- The Apex language is integrated with DML calls
- Inline Salesforce Object Query Language
- Easy to Use
- Easy to Test
- Version
- Multi-Tenant Aware Application
- Is Apex strongly typed language?
Yes, Apex is strongly typed. As it uses direct references to architectural objects such as sObject, any invalid references that fail if they are deleted or if they are of the wrong data type will fail quickly.
- Explain what a Map Class is in Apex Salesforce.
Map Classes in Apex Salesforce are:
- Classes that contain methods for the Map collection type.
- Maps are collections of key-value pairs where each key maps to a single value.
- Keys and values in a map can represent any data type, such as primitive types, collections, objects, or user-defined types.
- What does Batch Apex in Salesforce mean?
Batch Apex: You can define a single job that can be broken up into manageable chunks, whereas each chunk can be processed separately.
Using the batch apex, it will fetch all records on which you want to update a field, divide them into 200 records, and perform each operation separately on each 200 records.
This will allow us to execute on more than 10,000 records as it will not perform an operation on all the records in a single transaction but instead splits them into multiple subtasks (each containing up to 4000 records).
Example:
Our governing limits prevent us from updating every record of every account object in your organization, so we can’t accomplish the above task.
- How does Apex Scheduler work?
The Apex classes are invoked to run at a predetermined time.
Those who want to schedule their classes must implement the schedulable interface.
Schedule Interface:
It is possible to schedule the class that implements this interface to run at varying intervals. There are several methods within this interface.
Public void execute(schedulablecontext sc)
Public class mySchedule implements schedulable
{
Public void execute(schedulablecontext sc)
{
Account a = new Account(Name = ‘Accout User Name’)
Insert a;
}
}
- Are unit tests supported by Apex?
Apex provides built-in support for unit testing, including test results that indicate how much code is covered and where it may be possible to improve efficiency.
- How do Apex triggers work in Salesforce?
They are Apex code sequences that run before or after another. There are two main types of DML operations:
- Insert
- Update
- Delete
- Merge
- Upsert
- Undelete
- What are the different data types in Apex?
Different data types available in Apex are,
- Basic data type (Integer/Boolean/String)
- Boolean
- Date/Datetime/Time
- ID (18 bits and 15 bits, can be converted to and from String)
- Integer/Long/Double/Decimal
- String
- Blob
- Object
- Enum (enumeration type)
- sObjects ( sObjects/Account/Position_c, etc. )
- Collection (list, set, map, etc.)
- User-defined and system custom objects
- Null
- What does “Apex transaction” mean?
Apex transactions are groups of operations that need to be executed at the same time. The Data Manipulation Language (DML) is included, and it is responsible for querying records. When a DML operation fails, or if something goes wrong even with a single record, the entire transaction could be rolled back.
- What are the common methods of data types in Apex?
Data types are often represented by the following methods:
- 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
- What are The Types of Apex Triggers in Salesforce?
Triggers are divided into two categories
- Before Triggers
- After Triggers
Before Triggers:
By using Before Triggers, values can be updated or validated before they are saved to the database.
After Triggers:
Before Triggers can be used to access field values of records that are stored in the database and use them to modify other records.
Syntax:
Trigger trigger_name on Object_Name(trigger_events) { Code_block } WHERE trigger_events can be comma separated list of events.
- What are the limitations of Apex?
The Apex programming language is stored and executed in the cloud – the Force.com multi-tenant platform. Adding custom business logic to system events is possible with Apex, since it is tailored for data access and data manipulation on the platform. In spite of its many advantages for business process automation, it is not a general-purpose programming language.
Accordingly, Apex cannot be used to:
- Display elements in the user interface instead of error messages
- It cannot change standard features – Apex can only prevent them from happening or add new ones
- When a temporary file is created
- When threads are generated
- How does Apex Managed Sharing work?
Apex Managed Sharing enables developers to support applications to share requirements.
- It is available only to users who are authorized to modify all data permissions. These users are the only ones who can add/change apex-managed sharing.
- Sharing Reasons (Apex Sharing Reasons) are used in Apex Managed Sharing.
- Can switch statements be used with Apex?
The Apex language does not support switch statements.
- How does the apex program work within the VisualForce page?
We have to declare the Apex class in the following format when calling it from the VisualForce page.
< Apex : page controller = “class name “ >
When we call a VisualForce page that defines a controller attribute, the VisualForce page will create an object for the apex class defined in the controller first. In order to create an object for the apex class, the constructor must be called first.
- What are the types of statements we can use in Apex?
Apex must end with a semicolon, like Java; it can be a semicolon or a trailing semicolon:
- Assignment, such as assignment to a variable
- Condition (if-else)
- Loop: Do-While, While, For
- Locking
- Data manipulation language (DML)
- Transaction control
- Method call
- Exception handling (try catch)
- How does Salesforce’s Sandbox work?
The definition of a Sandbox is an isolated environment in which code can be tested and experiments can be conducted without affecting the production environment.
- What are the types of collections that Apex supports?
Apex supports the following types of collections:
- Lists (arrays)
- Maps
- Sets
- When do we use Sandbox?
Sandboxes come in handy when testing new applications on force.com or VisualForce pages. There is no way to test something in a production environment, so that creates a problem for the regular operation. Thus, developers use Sandbox to test applications in order to get around this problem.
There are different types of sandboxes available, including:
- Developer
- Developer pro
- Partial copy
- Full
- Describe how lists, maps, and sets are declared in Apex?
The Apex declaration method is similar to Java’s List/Map/Set method, except that direct assignment is allowed.
- 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’};
- Can you explain what Multitenant Architecture is in Salesforce?
Cloud computing is a technology that allows IT resources to be shared securely and efficiently.
- How does Apex handle sObjects?
Salesforce’s sObjects are special data types. Like a table in SQL, it contains fields that are similar to those in SQL. Standard sObjects and Custom sObjects can be used.
- The Onchange Event Does Not Work With <apex:actionsupport> In Internet Explorer 9. How To Resolve This Error?
It causes lots of problems in IE9 if we add the header to the Visualforce page. IE9 compatibility is made possible by a few java-script libraries loaded by Salesforce header. The best way to enable the header is to use “showHeader=true” in Apex pages.
- What are static resources?
Static resources allow you to add the content that you want to reference on the VisualForce page, such as images, Javascript, archives, CSS files, etc. An organization’s static resource may not exceed 250 MB in size.
- Please provide a simple example of how to use sObjects in Apex.
Below is the sample code for sObjects.
//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);
- How can you tell your Visualforce code to run in Ie8 compatibility mode if Ie9 is not working with your custom Visualforce page?
Add the following metatag to the page:
<meta http-equiv=”X-UA-Compatible” content=”IE=EmulateIE8″ />
- Describe the data types that can be stored in a Set
Each Set can store any of the following data types
- Collections
- User-defined types
- subjects
- Primitive types
- Built-in Apex types
- What is Enum in Apex?
An enumeration is an abstract data type that represents a set of defined identifiers in a finite amount of space. The keyword enumeration can be used to define an enumeration. Salesforce treats enumerations as any other data type.
- Could you give me an example of an Apex code for enumeration?
Here is the sample code for an enumeration.
You can do the following if you want to declare a possible name for the compound:
//Declaring enum for Chemical Compounds
Public enum Compounds {HCL, H2SO4, NACL, HG}
Compounds objC = Compounds.HCL;
System.debug(‘objC value: ‘+objC);
- In Many Cases, The Page Header is Already Set, So The Above Tips May Not Work. What is the best way to achieve the same result using Apex?
Put the following code in the constructor of Apex.
Apexpages.currentPage().getHeaders().put(‘X-UA-Compatible’, ‘IE=8’);
- So what exactly is a Visualforce component?
Visualforce components include widgets, user interface elements, panels, etc. They are reusable pieces of functionality. There are two types of VisualForce components, standard and custom, which are used to define the behavior of the user interface.
- What are the differences between DML and database methods?
The difference between database methods and DML statements,
DML Statement:
- It is not possible to update some records. The records in the list will be updated or not updated, depending on the number of records in the list.
- It is not possible to obtain a list of success and failure records.
- Example: insert listName;
Database Method:
- Partially update the database. In the Database method, the parameter true or false can be specified, true to allow partial updates, false to disallow them.
- The success and failure records can be obtained, as we saw in the examples.
- Example: Database.insert(listName, False), where false means partial updates are not permitted.
- How To Display The Formatted Number / Date In Visual Force? Which Component Should Be Used?
Use component “<apex:outputText>”.
Example : Format the number into currency.
<apex:outputtext value=”{0, number, 000,000.00}”>
<apex:param value=”{!valFromController}” />
</apex:outputtext>
OR
<apex:outputtext value=”{0, number, ###,###.00}”>
<apex:param value=”{!valFromController}” />
</apex:outputtext>
- What is SOQL?
The query language lets you construct simple, yet powerful query strings and specify the criteria by which the data should be selected from the platform database. The query language is called SOQL, or Salesforce Object Query Language.
- What are SOSL and SOQL methods in Salesforce Apex?
SOSL:
SOSL will be used to search for text strings across entire objects and fields. It is the object search language for Salesforce. You can search for specific strings across multiple objects.
SOSL evaluates a list of sObjects, each of which contains search results specific to that sObject type. In SOSL, the results list is always returned in the same order as the query.
SOQL:
This is similar to SOQL. You can use it to retrieve only one object record from an object. If you want to get the record from the parent or child object, you can write a nested query.
- The encrypted field needs to be displayed on Visualforce and you are using the component Apex:outputtext. Are encrypted fields supported by this component?
The encrypted custom fields embedded within the <apex:outputText> component display in clear text. View Encrypted Data permission is not respected by the <apex:outputText> component. In order to prevent sensitive data from being shown to unauthorized users, use the <apex:outputField> tag instead.
- What are the best practices for bulkification?
Trigger.New[0] is a bad index value since we never know how many records we will get in Trigger.New at runtime.
- It must be used for each loop, no matter how many records there are.
- SOQL should not be used inside a for loop.
- We should not use SOSL inside for loops.
- We should not use DML inside for loops.
- Data will be stored in collections, so our code will be able to handle single as well as multiple records.
- Describe Apex Call.
Apex calls refer to the process of executing Apex classes. Only one of these methods can be used to invoke the Apex class:
- the trigger or anonymous block
- in response to a specific event.
- Apex Asynchronous
- Apex classes can be scheduled to run in batches or at specified intervals.
- Web service class
- named Apex Email Service
- Apex Web Services allows you to expose your methods through SOAP and REST web services.
- Visualforce controller
- to handle inbound emails using Apex Email Service.
- You can call Apex using JavaScript.
- In Apex, the Web service methods are invoked using the Ajax toolkit.
- select Count(id), Name, Address__c From Opportunity GroupBy Name. Will this Query Work? Explain.
- This query will throw an error.
- Groupby clauses must use the columns that have been selected either in groupby clauses or in aggregate functions. Since the Name field is not used in aggregate methods or in groupby clauses, the error “Malformed Query” will result.
- What does database.insert(ListForBulkDML, True) mean?
Insert ListForBulkDML;
- What are the instances where batch processing of Apex is used?
Whenever you need to process a large number of records every day, or at specific intervals, you can use Batch Apex.
Similarly, if you wish to run an operation asynchronously, you can implement batch processing. Batch Apex is exposed as an interface that must be implemented by developers. It is possible to call batch jobs programmatically at runtime by using Apex. Using Batch Apex, the whole recordset is overwritten, and the process is broken down into manageable blocks of data.
- What Is The Difference Between Count() And Count(fieldname) In Soql?
COUNT()
- In the SELECT list, COUNT() must be the only element.
- It can also be used in conjunction with a LIMIT statement.
- If you are using ORDER BY, you cannot use COUNT(). Instead, use COUNT(fieldName).
- For API version 19.0 and later, you can’t use COUNT() with a GROUPBY clause. Instead, use COUNT(fieldName).
COUNT(fieldName)
- When ORDER BY clause is used on a field name, COUNT(fieldName) can be used.
- Using COUNT(fieldName) with a GROUPBY clause is supported for API versions 19.0 and later.
- In what ways can DML be partially performed?
We can partially accomplish this with database.insert(list, false);
- When debugging APEX code, how do you do it?
We have some debugging tools in Apex. Among them is system.debug(), which prints the value and output of a variable in the debug log.
Here are two tools you can use:
- Developer console
- Debug log
- When GroupBy Is Used In Soql, How Do You Write The “where” Clause?
The “Where” clause cannot be used with GroupBy, instead we need the “Having Clause”.
Example:
- We are looking for opportunities where more than one record contains “ABC” and the name exists more than once.
- SELECT COUNT(Id) , Name FROM Opportunity GROUPBY Name Having COUNT(Id) > 1 AND Name like ‘%ABC%’.
- The Datepicker Is The First Component Of The Vf Page. Then, when the page loads, Salesforce auto-focuses the first component, resulting in an Onfocus event for the Datepicker. This automatically opens the Datepicker component. How can we avoid this?
If you want to focus another field or an invisble component, write javascript code for the load event.
Example :
<span></span>
<script type=”text/javascript”>
/* prevent autopup of the date inputfield by the default focus behavoir */
window.onload=function() {
document.getElementById(‘focusDistraction’).focus();
}
</script>
- What is SOQL loop?
For loops of this type are used when we do not want to create a List and traverse the result of a SOQL query directly. During the next chapter, we will discuss more about SOQL queries. You should remember that the query specifies the records and fields it returns.
Syntax:
for (variable : [soql_query]) { code_block } (or) for (variable_list : [soql_query]) { code_block }
- What is the syntax of SOQL statements?
Syntax –
SELECT field1, field2,…. FROM Object_Type [WHERE condition]
Example:-Queries
List accountList = [SELECT ID, Name, FROM Account]; List accountList = [SELECT ID, Name, FROM Account WHERE annual revenue<10000];
- Describe Blob in Apex.
Blob: Binary storage type, usually used to receive uploaded attachment files.
- When you update or add the lead, how do you force the lead assignment rule in Apex?
The following steps are required to enforce Assignment Rules in Apex:
- Create the “Database.DMLOptions” class.
- The “useDefaultRule” property of “assignmentRuleHeader” needs to be set to True.
- Lastly, call the native method “setOptions” on your Lead instance, passing the Database.DMLOptions instance as an argument.
//This will enable the Apex Assignment Rules.
Database.DMLOptions dmlOptn = new Database.DMLOptions();
dmlOptn.assignmentRuleHeader.useDefaultRule = true;
leadObj.setOptions(dmlOptn);
- How would you explain GROUP BY?
When using API version 18.0 and later, you can group by with aggregate functions, such as sum() or max(), to summarize the data and enable you to rollup query results instead of processing individual records in your code.
Syntax: [ GROUP BY field GROUP BY LIST]
- How can Salesforce Apex determine which ID type to use?
ID: This type is unique to Salesforce and is used to identify the 18-bit identifier for a Salesforce object.
- Is it possible to access the enums defined by custom controllers in custom components?
Since the enum itself is not visible to the page and you cannot make it a property, we cannot reference it directly.
Example:
Apex class:
global with sharing class My_Controller {
public Case currCase {get; set; }
public enum StatusValue {RED, YELLOW, GREEN}
public StatusValues getColorStatus() {
return StatusValue.RED; //demo code – just return red
}
}
Visualforce page:
<apex:image url=’stopsign.png’ rendered=”{!colorStatus == StatusValue.RED}”/>
Above code snippet will throw error something like “Save Error: Unknown property‘My_Controller.statusValue’”
Resolution:
Add below method in Apex Controller:
public String currentStatusValue { get{ return getColorStatus().name(); }}
and change Visualforce code to
<apex:image url=’stopsign.png’ rendered=”{!currentStatusValue == ‘RED’}” />
- Can Salesforce Apex Statements Reference SOSL?
A SOSL statement evaluates a list of sObjects, where each list contains the search results for a specific sObject type. The results are always returned in the same order as they were specified in the query.
A SOSL query that does not return any results for a type of sObject will return an empty list for that type of sObject.
As an example, you can return a list of accounts, contacts, opportunities, and leads that begin with the phase map.
List < list < subject >> search list = [ find ‘map*’ In ALL FIELDS RETURNING Account (ID, Name), contact, opportunity, lead ];
Note:
- In the SOAP API, the FIND clause has a different syntax than the class on Apex.
- With Apex, the value of the FIND cause is delimited with single quotes.
Example:1
“map*” IN ALL FIELDS RETURNING account (Id, Name], Contact, Opportunity, Lead. The value of the FIND Clause is demarcated with braces in the Force.com API.
FIND {map*} IN ALL FIELDS RETURNING account [Id,name], contact ,opportunity,lead; From search list , you can create arrays for each object returned. Account [ ] accounts = (( list < accounts > ) search list [0] ); Contact [ ] contacts = [( list ) search list [0]) ; Opportunity [ ] opportunities = ((list < opportunity> ) search list [2]) ; Lead [ ] leads = (( list < lead> ) search list [3]);
- What is the method for converting a string to an integer?
To convert a string to an integer type, use valueOf(), for example:
Integer.valueOf(’12’); //12;
Integer.valueOf(’12a’); //throw TypeException
- When everything can be handled by a combination of a standard controller and an extension class, why is there a need for custom controllers in Visualforce?
By default, sharing settings are applied to standard objects/extensions; If we don’t want to apply sharing settings in our code, then Custom controller is our only option.
There is a possibility that the functionality of the page does not require Standard objects or may require more than one Standard object, in which case a Custom controller is required.
- How does Javascript remoting work for apex controllers?
JavaScript can be used to call apex controller methods from VisualForce using javascript remoting.
There are 3 parts to javascript remoting.
- JavaScript code that invokes the remote method on your VisualForce page.
- The definition of the remote method in your Apex controller class.
- The method definition is written in Apex, but there are a few differences from normal action methods.
- In the response, you will find a Javascript callback function you can include in your VF page.
- Where do you find the int method for converting long types to ints?
Long types are converted to int methods, such as intValue(), for example:
Long curLong = 20;
Integer myInt = curLong.intValue(); //20
- When we don’t write “with Sharing” in a class declaration, the code runs in system mode. Why does Apex introduce the keyword “without Sharing”?
Here is an example, classA is declared using “with sharing” and it calls classB’s method. When classB is not declared with any keywords then by default “with sharing” will be applied to that class since the originating call is through classA. In order to prevent this, classB must be explicitly defined with the keyword “without sharing”.
- How do I add javascript remoting to a Visualforce page?
Javascript remoting is enabled in a Visualforce page by adding the request as a javascript invocation:
Syntax –
[namespace.] controller.method ( [parameters …] Call back Function, [configuration] );- What does the contains method do in Apex?
You can use the contains() method to determine if a string contains a method for a specified string.
E.g:
String str1 = ‘abc’;
String str2 = ‘a’;
str1.contains(str2); //true
- If the user doesn’t have any rights on the record and only has read access at object level. Would he be able to change the owner of the record?
Yes. The “Transfer Record” option is available in the profile.
- Can you explain how to configure JavaScript remoting requests?
You can configure remoting requests by proving an object with configuration settings when declaring the request.
The following configuration parameters are supported by JavaScript remoting.
Name | Datatype | Description |
Buffer | Boolean | When requests are executed close together in time should be combined into a single request. By default, this is true. |
Escape | Boolean | Whether the apex methods response should be escaped. By default, this is true. |
Timeout | Integer | In milliseconds, the timeout for the Static Resource request. The default is 30000 (30 seconds). |
- Could you explain some string methods that you used in your projects?
While working on my previous projects, I used a variety of string methods, including,
1) startsWith() – The beginning of the string is specified.
2) endsWith()- Strings that end with a given string are not considered.
3) toUpperCase()- It is capitalized.
4) toLowerCase() – lowercase is changed.
5) length() – to determine the length of the string.
6) replace()- replaces the content matching the string.
7) split()- splits the string into a List collection based on the specified string.
8) trim()- removes spaces before and after the string.
9) indexOf() – which returns the index of the first match between the string and the given string, and -1 if no match is found.
10) lastIndexOf()- which gets the subscript of the last match between the string and the given string, and no results.
11) substring()- intercepts the string between the given subscripts in the string.
- Define Declarative Approach: What is it?
Developing a project without writing any code.
- What Are The Scenarios Where Share Object “mycustomobject__share” Is Not Available/Created For Custom Object “mycustomobject”?
Organization-wide default access levels for objects should not be set to the most permissive level. That is Public Read/Write access for custom objects.
- How do customizations and non-declarative approaches differ?
Working on a code-based project.
- What are some of the most commonly used date types?
There are many different Date and DateTime methods, so I’ll mention a few commonly used ones here,
1) Create a Date instance using newInstance().
E.g: Date d = Date.newInstance(2022,6,10); //2022-6-10
2) Use day() to determine what day it is.
E.g: Date d = Date.newInstance(2022,6,10); //d.day(); //10
3) Get the month from the date using month().
E.g: Date d = Date.newInstance(2022,6,10); //d.month(); //6
4) Use year() to determine the year of the date.
E.g: Date d = Date.newInstance(2022,6,10); //d.year(); //2022
5) With daysBetween(), find out how many days separate the two dates.
E.g: Date startDay = Date.newInstance(2022,6,10);
Date endDay =Date.newInstance(2022,7,8);
startDay.daysBetween(endDay); //28
6) Add the number of days with addDays().
E.g: Date d = Date.newInstance(2022,6,10); //d.addDay(3); //2022,6,13
7) getTime(), which returns the number of milliseconds that elapsed between 1970-01-01 00:00:00 and the calculation time.
E.g: DateTime d = Date.newInstance(2018,9,12,8,0,0);
d.getTime(); //1473681600000
- How To Get Picklist Values In Apex Classes?
We can accomplish this with Dynamic Apex. We call getDescribe() on objects of type pickilist. This is followed by getPicklistValues(). The result is iterated over and a list is created. Attach it to <apex:selectOptions>.
Code Example:
Let’s say we have a custom object called OfficeLocation__c. This object contains a picklist field Country__c.
The first thing we need to do, within our controller is use the getDescribe() method to obtain information on
the Country__c field:
DescribeFieldResult fieldResult = OfficeLocation__c.Country__c.getDEscribe();
We know that Country__c is a picklist, so we want to retrieve the picklist values:
List<Schema.PicklistEntry> ple = fieldResult.gerPicklistValues();
The only thing left for us to do is map the picklist values into an <apex:selectOptions> tag can use for display. Here is the entire method from our controller to do this:
public List<SelectOption> getCountries()
{
List<SelectOption> options = new List<SelectOption>();
Schema.DescribeFieldResult fieldResult =
OfficeLocation__c.Country__c.getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry f : ple)
{
options.add(new SelectOption(f.getLabel(), f.getValue()));
}
return options;
}
With our controller logic all complete, we can call the getCountries() method from our Visualforce page, and populate the <apex:selectList> tag:
<apex:selectList id=”countries” value=”{!Office_Location__c.Country__c}”
size=”1″ required=”true”>
<apex:selectOptions value=”{!countries}”/>
</apex:selectList>
- What operator should one use if one wants to actually compare the variable name in a query?
A comparison is made using the operator =.
- How does Apex differ from other companies?
The following are the characteristics of Apex
1) Integration
- DMLException, called in the DML language, includes insert, update and delete.
- This is the sObject type recode list, which is a combination of Salesforce Object Search Language (SOSL) and Salesforce Object Query Language (SOQL).
- Multiple records can be processed at the same time.
- Multiple updates are automatically avoided and locked.
- You can rebuild the saved Apex method and call the generic Force.com API from it
- When the referenced Apex custom object or custom project is edited or deleted, it will be warned.
2) More convenient for users
Variables and syntax components, modules, conditional declarations, loop declarations, and objects and arrays are all based on Java. Due to Apex’s ease of use when importing new features, the Force.com platform can run more efficiently and develop Apex.
3) Pointing to the data
Similarly, on the Force.com platform server, multiple Apex queries and DML statements are designed to a session in the database server by the database stored procedure. Apex does not support the execution of stored procedures on the user interface, as other databases do.
4) Clear as crystal
Strongly typed languages such as Apex refer directly to the schema object by its object name and project name. A compilation error will occur if this reference is not available when the reference cannot be found. The standard items in the master data and the class associations are saved in order to prevent the referenced Apex code from being deleted.
5) Self-determination
Apex is a language based on Force.com’s implementation, control, and control.
6) Residential multi-tenancy
Apex is implemented in a rented environment, like other Force.com platforms. Apex’s real-time engine avoids code interference, and the shared code is not occupied by a single tenant to accommodate this environment. An easy-to-understand error message appears when the code that violates the rule fails to execute.
7) Upgrades are automatic
Upgrades to other parts of the Force.com platform do not need to be described directly in Apex. Due to the fact that the compiled code is saved in the platform as master data, Apex has been upgraded as well.
8) Simple to test
How much of the code is covered in Apex? Is it more effective than another part of the code? Each is represented in the test results, etc., and can be tested and executed independently. All the individual tests in SalesForce had been run before the platform upgrade, and all standard Apex code had been executed as expected.
9) Maintain version control
Consequently, a version of the Apex code change can be stored in the Force.com API. In this way, normal operation can be maintained. Apex consists of Performance Edition, Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com.
- What Are The Different Types Of Controllers In Visualforce?
Visual Force pages have two types of controllers.
- Standard Controller
- Custom Controller
- What are the two benefits of writing controllers?
Logic & data are delivered to us.
- Under what conditions may Apex be used?
SalesForce combines different functions that provide CRM (customer relation management) applications. In other words, SalesForce is a custom application that integrates with the corresponding company. However, many organizations lack the ability to integrate complex business processes. Senior administrators and developers can package a variety of methods on the SalesForce platform. Apex, VisualForce, and Soap APIs are among these methods.
1) Apex – Apex should be used for the following occasions
- Provider of web services
- To create a mail service
- That detects multiple complex objects
- Create complex business processes not supported by workflow
- Create a custom transaction (not just a record, object, or the logic of the transaction)
2) Visualforce
- Using Visualforce, developers can develop user interfaces while creating efficient interfaces using tag-based tagging. Using VisualForce, you can accomplish the following.
- Add other multiple steps, such as weChat
- Develop custom controllers independently for each application
- Defining navigation patterns and inherent rules for the most effective and appropriate application interactivity.
3) SOAP API
The need to manage only one record type at a time, and manage transactions (savepoint settings and rollbacks of changes, etc.) cannot be accomplished using a standard SOAP API call without adding functionality to the composite application.
- Can more than one controller be used on the same VF page?
Salesforce can only be used with one controller. For everything else, Controller extensions are available.
It is possible to have more than one Controller extension.
Example:
<apex:page standardController=”Account”
extensions=”ExtOne,ExtTwo” showHeader=”false”>
<apex:outputText value=”{!foo}” />
</apex:page>
- The method of ExtOne will be executed if ExtOne and ExtTwo both have the getFoo() method.
- CustomControllerName is the name of a custom controller that you wish to extend. Every Apex class that has a constructor that takes a single argument of typeApexPages.StandardController or CustomControllerName qualifies as a controller extension.
- What are two reasons why we prefer VFP to configurations (no coding)?
You can include multiple edits, inserts, javascript, and angular js.
- What is the difference between * apex:inputText / > and * apex:inputField / >?
The inputField object copies a field from any object and displays it on a VF page, just like copy-paste.
Creating a field from scratch will be easy with inputText.
- How does Apex perform its functions?
- com’s cloud platform compiles, saves, and executes Apex.
- As soon as the developer saves the Apex code, the cloud platform’s application server converts the abstract settings into assembly code that can be recognized by the background according to the Apex real-time translator. The commands are then saved to the cloud platform as metadata.
- By clicking the button, the user will access the VisualForce screen to execute the Apex code.
- In the cloud platform, the application server obtains the compiled command from the metadata, passes it to the cloud through the real-time program translator, and then returns the running result.
- End users are not concerned with the requirements of cloud platforms or the difference in execution times.
- What does System.runas() do?
In general, all Apex code runs in system mode, and permissions and record sharing are not considered. You can write test methods that change user contexts to an existing user or a new user by using the System.runAs() method. Those users’ record sharing is then enforced. Only test methods can use runAs. After all runAs() test methods have completed, the original system context is started again.
Example:
runAs(u) {
// The following code runs as user ‘u’
System.debug(‘Current User: ‘ + UserInfo.getUserName());
System.debug(‘Current Profile: ‘ + UserInfo.getProfileId()); }
// Run some code that checks record sharing
}
90. What does Test.setpage() do?
- It sets the context to the current page, which is normally used for testing the visual force controller.
- Is it possible to call javascript from a VisualForce page?
Javascript file can be added in Static Resource setup -> develop -> Static Resources -> click on ‘New’ -> Name: filename, and add the file from the local desktop.
- How does Future Annotation(@Future) work?
To specify that these methods will be executed asynchronously, use the future annotation.
- Static methods must be used on methods with future annotations
- void types can only be returned by methods with future annotations.
Syntax:
global class class_name { @future Static void methodname(parameters) { //body of the method } }
- In Apex, how can I round a double to two decimal places?
Decimal d = 100/3;
Double ans = d.setScale(2);
- Can you describe the AppExchange directory?
Salesforce customers can review, demo, comment on, and/or install hundreds of app exchange apps. If developers wish to share their apps with the community, they can submit them to the appexchange directory.
- Is it possible to create master-detail relationships with existing records?
No. First, we create the lookup relationship, then populate the value on all existing records, and finally convert them.
- To create selectable values for radio buttons and picklists, which tag is used?
The <Apex:selectoption> method is used.
- What is the process of executing validation rules? Is it dependent on Visualforce / Page Layout?
Validation rules are run at the model level, so they are not affected by the user interface. Salesforce runs the validation rules for any record it saves.
- What Are The Differences Between Database.insert And Insert?
- DML statement insert has the same meaning as databse.insert.
- In contrast, database.insert gives more flexibility, such as rollback, default assignment rules, etc. The method setOptions(Database.DMLOptions) allows us to achieve the database.insert behavior for insert.
The most important difference is:
- In bulk operations, if an error occurs using the DML statement (insert), the execution will stop and the Apex code will throw an error that can be caught in a try/catch block.
- When DML database methods are used (Database.insert), then if an error occurs, the remaining records will be inserted / updated, meaning partial DML will be done.
- How can a custom index not include a certain field?
Salesforce does not allow formula fields to be added to custom indexes.
- How are triggers and workflows different?
Workflow:
- Workflow is a process that fires an action based on evaluation criteria and rule criteria.
- Workflow can be accessed across objects.
- DML operations cannot be performed on workflows.
- Database queries cannot be performed on workflows.
Trigger:
- Triggers are pieces of code that execute before or after a record is inserted or updated.
- They can be accessed across objects and related to them.
- Twenty DML operations can be performed in a single trigger.
- Twenty SOQL queries can be used in a single trigger.
- Which apex classes are commonly used within a project?
Standard controllers, select options, page references, messages, etc.
- How Do Static Variables Work?
A static method or variable will be initialized only once when a class is loaded. During the view state of a Visualforce page, static variables are not transmitted.
Within the scope of a request, static variables are only static. The variables are not static across the entire server or organization.
- Is There Any Other Way To Get Custom Settings Apart From Soql And Sosl?
In addition to SOQL or SOSL, Custom settings have their own set of methods for accessing records.
For example:
When ISO_Country is set to a custom name,
SO_Country__c code = ISO_Country__c.getInstance(‘INDIA’);
//To return a map of data sets defined for the custom object (all records in the custom object), //you would use:
Map<String,ISO_Country__c> mapCodes = ISO_Country__c.getAll();
// display the ISO code for India
System.debug(‘ISO Code: ‘+mapCodes.get(‘INDIA’).ISO_Code__c);
//Alternatively you can return the map as a list:
List<String> listCodes = ISO_Country__c.getAll().values();
- How does the transient keyword affect the search results?
Data cannot be saved into view state while transient is present. These variables are meant for short-term use.
- When we use the VisualForce page, how many field dependencies can we use at one time?
A VisualForce page can have a maximum of 10 field dependencies.
- If a child has two master records and one is deleted, what happens?
We will delete the child’s record.
- What Is The Difference Between Render, Rerender, And Renderas In Visualforce?
render: Similar to the “display” property of CSS. This property is used to show or hide elements.
rerender: What component should be refreshed after Ajax – available on commandlink, commandbutton, actionsupport, etc.
renderas: The page can be rendered as a pdf, doc, or excel file.
- How do I get the Salesforce security token?
Simply click on your name, then click Personal, and you will see the option to reset your security token.
- What does a metadata-driven development model entail?
Model for app development in which apps are defined as declarative “blueprints,” without requiring code. Metadata describes data models, objects, forms, workflows, and more.
- How does S-Control work?
Salesforce.com widgets that are entirely based on JavaScript are known as S-Controls. These widgets run at the client side but are hosted by Salesforce.com. The S-Controls have been replaced by VisualForce.
- In Salesforce, how do you get a list of all available objects using Apex (dynamic Apex)?
Map<String, Schema.SObjectType> m = Schema.getGlobalDescribe();
- Dynamically creating instances of Sobject? The SObject Is Normally Created Like “account A = New Account()”. In What Situation Would You Not Know Which SObject Is Going To Be Instantiated? The Decision Will Be Made At Runtime, So What Will You Do?
public SObject getNewSobject(String t){
// Call global describe to get the map of string to token.
Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
// Get the token for the sobject based on the type.
Schema.SObjectType st = gd.get(t);
// Instantiate the sobject from the token.
Sobject s = st.newSobject();
return s;
}
- How does Salesforce’s wrapper class work?
Wrappers or containers are data structures, class types, or abstract data types used to hold multiple collections of objects. In VisualForce, it allows multiple objects to be displayed in a single table.
- What is a force platform site?
Integrate your Salesforce organization directly with public websites and applications without requiring users to log in.
- How Do I Get All The Fields Of SObject Using Dynamic Apex?
Map<String, Schema.SObjectType> m = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(‘API_Name_Of_SObject’) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap();
- How Do I Dynamically Get All The Required Fields Of SObject?
In Apex dynamic API, the required field cannot be represented directly by a property. It can however be discovered by another means.
It is mandatory if any field has one or more of the following properties.
- Create it if it is possible
- and it is not nillable
- when it does not have a default value
Map<String, Schema.SObjectType> m = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(so.apiName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
for(String f : fields.keyset())
{
Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
{
//This is mandatory/required field
}
}
- What exactly is a tab in Salesforce?
Tabs are user interfaces that display custom object data or other embedded web content. Salesforce tabs fall into three categories, which are:
- Custom Tabs.
- Visualforce Tabs.
- Web Tabs.
- What types of email templates can be created in Salesforce?
The following is a list of templates available in Salesforce:
Text Template: Any user can modify or change this template.
HTML with letterhead: This email template can be created by administrators and users with Edit HTML permission.
Custom HTML: This email template can be created without a letterhead by administrators and users who have Edit HTML permission. It requires knowledge of HTML or access to HTML code in order to insert it into the email template.
Visualforce Email Template: VisualForce administrators and developers can only create this template. This template can merge data from different records.
- How Does Property In Apex Work? Please explain with advantages.
The syntax of Apex is mostly derived from the well-known programming language Java. In Java, encapsulating variables is done by declaring them private and then creating setters and getters for them.
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
In Apex, however, the concept of property was introduced from C# as shown below:
public String name {get; set;}
It is easy to see that the code is simple and that instead of using nearly 8 to 11 lines, it is done in just one line. This will be very useful when an Apex class contains a lot of members. A second advantage is the “number of lines of code” limitation by Salesforce, which will be greatly reduced.
- How Does The Controller Extension Work?
The term controller extension refers to any Apex class with a public constructor that accepts a Custom Controller or Standard Controller object as a single argument.
- We can share records based on specific conditions, such as sharing records with a group of users. What are the steps to follow if India meets the country criteria?
Setup → Security Controls → sharing settings → Click on ‘Edit’
Apex sharing: Share objects are available for every object. To share records using Apex we need to create records in the shared object.
- Is The Controller Extension Necessary Or Important?
- Recently, Salesforce introduced a very useful and important concept called controller extension. Programmers can extend the functionality of existing custom controllers or standard controllers.
- It is possible to have one Custom controller or standard controller in a Visualforce but many controller extensions.
- The custom extension is the supporter of a custom or standard controller.
- As an example, if one controller is written and used by multiple Visualforce pages, and one of them needs some extra logic. We can then create a controller extension and apply it only to that page, instead of writing that logic to controllers (which can be used by many visualforce pages).
- Is It Possible To Read The Parameter Value From The Url In Apex?
This parameter has the name “RecordType”.
String recordType = Apexpages.currentPage().getParameters().get(‘RecordType’);
- In Salesforce, one object can have two triggers, both of which are run “before insert”. Do these triggers have a way to control the order in which they are executed?
According to Salesforce.com, trigger sequences cannot be predefined. It is best practice to create one trigger per object and to use comment blocks to separate different logic blocks. It may also be possible to optimize SOQL queries if all logic is inside one trigger.
- In a production environment, is it possible to edit the VisualForce page?
Certainly! Both in the production environment and in a sandbox, we can create and edit VisualForce pages. A VisualForce page can only add the unique values in a sandbox, which you can’t do in a production environment.
- In the production function, is it possible to modify the apex trigger/apex class?
In order to edit the apex trigger/apex class that should be done in a sandbox environment, you cannot do that.
- What Are The Differences Between Trigger.new And Trigger.old In Apex – SfDC?
Trigger.new:
- Provides a list of the new versions of the sObject records
- The sObject list is available only in insert and update triggers
- For example, Trigger.new is available before insert, after insert, before update, and after update
- new allows records to be modified only in before triggers.
Trigger.old:
- Shows the previous versions of a record.
- The sObject list is only available in triggers for updating and deleting.
- In other words, Trigger.old can be accessed after insert, after update, before delete, and after update.
- Is It Possible To Limit Any Trigger To Fire Only Once?
- There can be two triggers: one that fires before workflows, and one that fires after workflows.
- The before and after triggers fire again only if something needs to be updated.
If the fields are already set, the triggers aren’t fired.
Workaround:
public class HelperClass {
public static boolean firstRun = true;
}
trigger affectedTrigger on Account (before delete, after delete, after undelete) {
if(Trigger.isBefore){
if(Trigger.isDelete){
if(HelperClass.firstRun){
Trigger.old[0].addError(‘Before Account Delete Error’);
HelperClass.firstRun=false;
}
}
}
}
- Which options are available for customizing page layouts?
You can customize objects or records on a page by using page layouts. They allow you to customize or design the page according to your needs. They help you customize the layout of the page. You can customize things like buttons, fields, custom links, and related lists from this page.
- Invoking batch apex job programmatically (or) executing batch apex job programmatically?
To start a batch job programmatically, we can use the database.executebatch ( ) method.
Syntax:
- Execute batch with public static IDs ( sObject class name)
- Execute batch with public static IDs (sObject class name, integer scope)
- Both of the above methods are static methods of the database class. The batch job can be executed using either of the methods.
- Will Visualforce still be able to use merge fields just like S-Control?
Yes. S-Controls work the same way. Embedded merge fields are supported by Visualforce pages.
- Which keyword is helpful when passing the collection to the query rather than passing one value?
IN – keyword.
Final Thoughts:
The above list of Salesforce Apex Interview questions is pretty comprehensive and should give you enough background knowledge about everything Salesforce-related. Hopefully, these Salesforce beginner interview questions will help you prepare for any upcoming interviews. Do let us know how did you do.
We have created a series of courses and guides on Salesforce Apex as well. If you want more detail please call us at +91 9989432324 or contact us now.