Welcome to Salesforce Apex Interview questions. In this Salesforce Interview questions guide, we have listed important Apex basics, object-oriented concepts, collections, sharing rules, SOQL, DML, triggers, testing, and scenario-based questions that are commonly discussed in Salesforce developer interviews.
Apex is usually tested through short definitions first, followed by practical questions such as how to avoid governor limit errors, how to bulkify code, when to use a trigger, how sharing behaves in classes, and how to write reliable test classes. Use the questions below as a revision checklist before a Salesforce developer interview.
Salesforce Apex interview questions on Apex basics
What is Apex?
Salesforce Apex language is a multi-purpose programming language and exists in multi-tenant Environment. Every Resource that executed using Apex Programming language are effectively controlled for high quality of service to all Salesforce developers.
In simple terms, Apex is Salesforce’s strongly typed, object-oriented programming language used to run custom business logic on the Salesforce Platform. It is commonly used in triggers, classes, batch jobs, scheduled jobs, REST/SOAP services, and controller logic. Apex runs on Salesforce servers and is subject to governor limits because Salesforce is a multi-tenant platform.
What API is used in Apex?
Apex code can work with Salesforce data through platform features such as SOQL, SOSL, and DML. Apex can also expose or consume APIs. For example, an Apex class can be exposed as a REST service by using annotations such as @RestResource, @HttpGet, and @HttpPost. Apex can also call external systems using HTTP callouts.
@RestResource(urlMapping='/accountService/*')
global with sharing class AccountService {
@HttpGet
global static Account getAccount() {
RestRequest request = RestContext.request;
String accountId = request.requestURI.substringAfterLast('/');
return [SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1];
}
}
What are access modifiers in Apex?
Access modifiers control where an Apex class, method, or variable can be used. Common Apex access modifiers include private, public, global, and protected.
privateis accessible only within the defining class.publicis accessible within the same application or namespace.globalis accessible across namespaces and is required for some managed package and web service use cases.protectedis available to the defining class and its subclasses.
What is the difference between with sharing and without sharing in Apex?
with sharing means the class enforces the current user’s record sharing rules. without sharing means the class does not enforce the current user’s record sharing rules. This affects record visibility, not field-level security or object permissions by itself.
public with sharing class AccountReaderWithSharing {
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
public without sharing class AccountReaderWithoutSharing {
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account LIMIT 10];
}
}
In interviews, mention that sharing keywords should be chosen deliberately. For security-sensitive code, it is also important to check CRUD, field-level security, and user mode data access where applicable.
Apex class, constructor, static variable, and reference variable interview questions
What is a constructor in Apex?
A constructor is a special method that runs when an object of a class is created. It has the same name as the class and does not have a return type. Constructors are used to initialize variables or prepare default state.
public class InvoiceCalculator {
Decimal taxRate;
public InvoiceCalculator() {
taxRate = 0.18;
}
}
Can I have a constructor with parameters in Apex?
Yes. Apex supports parameterized constructors. They are useful when an object should be initialized with values supplied by the caller.
public class InvoiceCalculator {
Decimal taxRate;
public InvoiceCalculator(Decimal rate) {
taxRate = rate;
}
}
What is the use of static variables in Apex?
A static variable belongs to the class rather than to a specific object instance. In Apex, static variables are often used to store transaction-level state, utility values, or trigger recursion guards. Static values do not persist permanently; they are reset between transactions.
public class TriggerControl {
public static Boolean isFirstRun = true;
}
What are reference variables in Apex?
A reference variable stores a reference to an object, not the entire object data directly. For example, when a variable refers to an Account object, the variable points to that object in memory. If two variables refer to the same object, changes made through one reference can be visible through the other reference.
Salesforce Apex interview questions on sObjects and collections
What are sObjects in Apex?
An sObject is a Salesforce object record in Apex. Standard objects such as Account, Contact, and Opportunity are sObjects. Custom objects are also sObjects and usually end with __c, such as Invoice__c.
Account acc = new Account();
acc.Name = 'TutorialKart Customer';
insert acc;
What is the difference between List and Set in Apex?
A List is an ordered collection that can contain duplicate values. A Set is an unordered collection that stores unique values. Lists are useful when order matters or duplicates are allowed. Sets are useful when you need uniqueness, such as collecting record IDs before a query.
List<String> names = new List<String>{'Apex', 'Apex', 'SOQL'};
Set<String> uniqueNames = new Set<String>{'Apex', 'Apex', 'SOQL'};
System.debug(names.size()); // 3
System.debug(uniqueNames.size()); // 2
What is Map in Apex?
A Map is a collection of key-value pairs. Each key maps to one value. Maps are widely used in Apex to look up records efficiently by Id or another unique key.
Map<Id, Account> accountMap = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
for (Id accountId : accountMap.keySet()) {
System.debug(accountMap.get(accountId).Name);
}
Can we have duplicate keys in Map in Apex?
No. A Map cannot contain duplicate keys. If you add another value using an existing key, the new value replaces the old value for that key.
How many objects can we store in a List in Apex?
Apex collections are subject to Salesforce governor limits, heap size, and transaction limits. Instead of memorizing only a number, interviewers usually expect you to explain that large lists should be handled carefully, queries should be selective, and processing should be bulkified. For very large data volumes, use Batch Apex, Queueable Apex, or another asynchronous pattern as appropriate.
Salesforce Apex interview questions on properties, PageReference, and Visualforce
What are setter and getter methods in Apex?
Getter and setter methods are used to read and write property values. In Apex, properties can be written with { get; set; }. They are commonly seen in Visualforce controllers and controller extensions.
public class CustomerController {
public String customerName { get; set; }
public CustomerController() {
customerName = 'Acme';
}
}
How do you refer to current page id in Apex?
In a Visualforce controller, you can read the current page parameter using ApexPages.currentPage().getParameters().get('id'). This is commonly used when the page is opened with a record id in the URL.
Id recordId = ApexPages.currentPage().getParameters().get('id');
How do you invoke standard actions in an Apex class?
In Visualforce, standard controller actions such as save, edit, delete, and cancel can be used through the standard controller. A custom controller extension can receive an ApexPages.StandardController instance and call standard behavior where appropriate.
public class AccountExtension {
private ApexPages.StandardController controller;
public AccountExtension(ApexPages.StandardController controller) {
this.controller = controller;
}
public PageReference saveAccount() {
return controller.save();
}
}
What is PageReference in Apex?
PageReference represents a reference to a Visualforce page or URL. It can be used to redirect the user, set URL parameters, or control page navigation from Apex controller logic.
PageReference pageRef = new PageReference('/' + recordId);
pageRef.setRedirect(true);
return pageRef;
How do you pass parameters from one Apex class to another?
You can pass values from one Apex class to another through method parameters, constructor parameters, properties, or wrapper objects. In Visualforce navigation, you can also pass values through page URL parameters and read them with ApexPages.currentPage().getParameters().
Apex object-oriented programming interview questions for experienced developers
What is a virtual class in Apex?
A virtual class is a class that can be extended by another class. A virtual method can be overridden in a child class. Use virtual when you want to provide a default implementation but still allow customization in subclasses.
public virtual class PaymentService {
public virtual Decimal calculateFee(Decimal amount) {
return amount * 0.02;
}
}
What is an interface in Apex?
An interface defines method signatures that implementing classes must provide. Interfaces are useful when different classes need to follow the same contract while keeping their own implementation logic.
public interface DiscountRule {
Decimal applyDiscount(Decimal amount);
}
public class StandardDiscount implements DiscountRule {
public Decimal applyDiscount(Decimal amount) {
return amount * 0.90;
}
}
What is an abstract class in Apex?
An abstract class cannot be instantiated directly. It can contain abstract methods and implemented methods. Abstract classes are useful when related classes share common logic but must implement some behavior differently.
public abstract class NotificationSender {
public abstract void send(String message);
public Boolean isMessageValid(String message) {
return String.isNotBlank(message);
}
}
What is overloading in Apex?
Overloading means creating multiple methods with the same name but different parameter lists. The return type alone is not enough to overload a method.
public class TaxCalculator {
public Decimal calculate(Decimal amount) {
return amount * 0.18;
}
public Decimal calculate(Decimal amount, Decimal rate) {
return amount * rate;
}
}
What is overriding in Apex?
Overriding means a child class provides its own implementation of a method defined in a parent class. In Apex, the parent method must be marked virtual or abstract, and the child method uses the override keyword.
public virtual class BasePriceService {
public virtual Decimal getPrice() {
return 100;
}
}
public class DiscountPriceService extends BasePriceService {
public override Decimal getPrice() {
return 90;
}
}
Apex sharing behavior interview questions with class inheritance
When we invoke a with sharing method in a without sharing class, how is it executed?
The sharing behavior depends on the class where the method is defined and how the call stack applies sharing rules. If a method belongs to a class declared with sharing, the queries and DML in that class follow sharing rules. If a method belongs to a class declared without sharing, sharing rules are not enforced for that class. In interviews, explain the exact class boundary rather than giving a one-word answer.
Will an inner class inherit the sharing properties of the outer class?
An inner class does not automatically inherit the sharing declaration of the outer class in every situation. Define sharing explicitly on classes where record visibility matters. This avoids accidental behavior and makes the security model easier to review.
Base class is declared as with sharing and derived class is declared as without sharing. What will happen?
The sharing keyword on the class whose method is executing controls the behavior for that class. If the derived class is declared without sharing, code executed in that derived class does not enforce record sharing rules. If a method in the base class runs under a with sharing class, that method follows sharing rules. The safest interview answer is to explain the execution context class by class.
Scenario-based Salesforce Apex interview questions on SOQL, DML, and triggers
Why should Apex code be bulkified?
Apex code should be bulkified because triggers and classes may process many records in a single transaction. Bulkified code avoids SOQL and DML inside loops, uses collections, and performs queries and DML operations in batches. This helps avoid governor limit exceptions and makes code safer for imports, integrations, and mass updates.
What is wrong with SOQL inside a for loop?
SOQL inside a loop can run one query for each record. If many records are processed, the transaction may exceed the SOQL query governor limit. The better approach is to collect record IDs in a Set, query related records once, store them in a Map, and then process the records in memory.
Set<Id> accountIds = new Set<Id>();
for (Contact con : Trigger.new) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
What is the difference between before trigger and after trigger in Apex?
A before trigger runs before records are saved to the database. It is useful for changing field values on the same records before save. An after trigger runs after records are saved and record IDs are available. It is useful for creating or updating related records that depend on saved data.
How do you avoid recursive trigger execution in Apex?
A common approach is to use a static variable in a helper class to track whether the trigger logic has already run in the current transaction. This should be used carefully so that it does not block legitimate bulk processing paths.
public class AccountTriggerGuard {
public static Boolean hasRun = false;
}
if (!AccountTriggerGuard.hasRun) {
AccountTriggerGuard.hasRun = true;
// Trigger logic here
}
Apex interview questions on null pointer errors and exception handling
What is a dereferencing a null pointer value error in Apex?
A dereferencing a null pointer value error occurs when Apex code tries to access a property or method on a variable that is currently null. This commonly happens when a query returns no record, a map lookup returns no value, or an object was declared but not initialized.
Account acc;
System.debug(acc.Name); // Null pointer error
Fix it by initializing the object or checking for null before using it.
Account acc = new Account(Name = 'Test Account');
if (acc != null) {
System.debug(acc.Name);
}
How do you handle exceptions in Apex?
Apex exceptions can be handled using try, catch, and finally. Use exception handling when an operation can fail and you need controlled behavior, such as logging the error or returning a useful response. Avoid swallowing exceptions without action, because that can hide real data or logic problems.
try {
insert new Account();
} catch (DmlException ex) {
System.debug('DML failed: ' + ex.getMessage());
}
Salesforce Apex testing interview questions for developer roles
Why are test classes required in Apex?
Test classes verify that Apex code behaves as expected before deployment. They also help prevent regressions when code changes. A good Apex test creates its own test data, exercises the code path, and uses assertions to verify the result.
What is the purpose of Test.startTest() and Test.stopTest()?
Test.startTest() and Test.stopTest() create a fresh set of governor limits for the code being tested and help execute asynchronous code during a test method. They are commonly used when testing future methods, queueable jobs, batch jobs, and scheduled Apex.
@IsTest
private class AccountServiceTest {
@IsTest
static void createsAccount() {
Test.startTest();
Account acc = new Account(Name = 'Test Account');
insert acc;
Test.stopTest();
Account saved = [SELECT Id, Name FROM Account WHERE Id = :acc.Id];
System.assertEquals('Test Account', saved.Name);
}
}
Original Salesforce Apex interview questions list for quick revision
The following quick list keeps the original Apex interview question set for revision.
- What API is used in the apex?
- What are the access modifiers in the apex?
- What is the difference between With Sharing and Without Sharing ?
- What is a constructor?
- What is the use of the static variables?
- What are reference variables in apex?
- What are Sobjects?
- What is the difference between List and Set?
- What is Map in apex?
- Can we have duplicate Keys in Map
- How many objects we can store in list ?
- What are setter and getter methods?
- How do you refer to current page id in apex?
- How to do you invoke standard actions in apex class?
- What is page reference?
- How do you pass the parameters from on apex class to another to another?
- What is virtual class?
- What is interface?
- What is abstract class?
- What is overloading?
- What is overriding?
- When we invoke with sharing method in without sharing class .Now method is Executed as?
- Will the inner class inherits the sharing properties of outer class?
- Base class is declared as With Sharing and Derived class is declared as without
- Sharing what will happen?
- Can I have constructor with parameters in apex?
- Dereferencing a Null pointer value error?
QA checklist for Salesforce Apex interview questions page
- Check that every Apex interview question has a direct answer, not only a question list.
- Confirm that Apex code examples avoid SOQL and DML inside loops unless the example is intentionally showing a mistake.
- Verify that sharing explanations distinguish record sharing from CRUD and field-level security.
- Review collection examples for correct use of
List,Set, andMap. - Check that test class examples create their own data and include assertions.
- Confirm that scenario-based questions cover bulkification, triggers, exceptions, and asynchronous Apex at an interview-ready level.
FAQs on Salesforce Apex interview questions
What Apex topics should I revise first for a Salesforce developer interview?
Start with Apex basics, sObjects, collections, SOQL, DML, triggers, governor limits, sharing keywords, test classes, and asynchronous Apex. These topics are used in both beginner and experienced Salesforce developer interviews.
Are Salesforce Apex interview questions mostly theory or coding based?
They are usually a mix of both. Basic rounds may ask definitions such as List versus Set or with sharing versus without sharing. Developer rounds often include scenario-based questions about bulkification, trigger design, SOQL optimization, test data, and integration logic.
How should I answer governor limit questions in an Apex interview?
Explain that Apex runs in a multi-tenant environment and governor limits protect shared resources. Then describe practical solutions such as avoiding SOQL in loops, using collections, writing bulkified triggers, using selective queries, and moving long-running work to asynchronous Apex when suitable.
What is the best way to explain with sharing and without sharing in Apex interviews?
Say that with sharing enforces the current user’s record sharing rules, while without sharing does not. Also mention that sharing keywords do not automatically replace object permission and field-level security checks.
Do Apex interview answers need code examples?
For experienced Salesforce developer roles, code examples help. Short examples for maps, bulkified SOQL, constructors, test classes, and trigger guards make the answer clearer and show that you can apply the concept in real Apex code.
TutorialKart.com