Salesforce Apex interview questions and answers
Apex comes up in every developer interview, usually within the first ten minutes. Work through these and you will have covered collections, DML, sharing, async processing and the habits interviewers listen for.
On this page (14 sections)
Apex language basicsDML, SOQL and exceptionsTriggersAsynchronous ApexSharing and security in ApexCallouts and Platform EventsTesting ApexDesign and performanceCommon Mistakes in Apex InterviewsInterviewer Follow-Up PatternsReal Project Experience SignalsRelated Apex Interview QuestionsFrequently Asked Questions about Apex InterviewsRelated ResourcesNew to this topic? Learn Apex step by step before you practise.
Apex is at the core of Salesforce development. These 45 interview questions cover everything from basic syntax and collections to advanced patterns like Batch Apex, Platform Events, and dynamic SOQL. Each answer includes practical explanations and the reasoning behind best practices. They are useful for the Platform Developer (PD1) exam and for senior developer interviews.
Questions in each topic go from beginner to advanced. Use On this page to jump to the topic you need.
Apex language basics
01What is Apex and how does it differ from Java?
What is Apex and how does it differ from Java?
Apex is Salesforce's proprietary, strongly-typed programming language that runs on Salesforce servers. While syntactically similar to Java, key differences include: Apex runs in a multi-tenant environment with governor limits, has built-in DML operations, supports SOQL/SOSL natively, and includes native support for triggers and test classes. Unlike Java, Apex doesn't support creating threads, has limited library access, and requires test coverage for deployment.
02Explain collections in Apex: List, Set, and Map.
Explain collections in Apex: List, Set, and Map.
What the interviewer is checking: Whether you can pick the right collection in a real scenario, such as a Set of Ids for a query and a Map to match children to parents.
List is an ordered collection that allows duplicates. Use it when order matters or you need index-based access. Set is an unordered collection of unique elements. Use it for deduplication and efficient contains() checks. Map stores key-value pairs with unique keys. Use it for O(1) lookups: the most common pattern is Map<Id, SObject> for efficient record access. Maps are essential for bulkification; they let you avoid nested loops and SOQL inside loops.
Common mistake: Giving definitions only, with no example of how a Map avoids SOQL inside a loop.
03What are Apex enums and when should you use them?
What are Apex enums and when should you use them?
Enums define a fixed set of constants. Declare with: public enum Season { WINTER, SPRING, SUMMER, FALL }. Use them for status values, types, and categories instead of hardcoded strings. Benefits: type safety (compiler catches invalid values), self-documenting code, and IDE autocomplete. Use in switch statements for clean branching. Salesforce provides built-in enums like System.TriggerOperation (BEFORE_INSERT, AFTER_UPDATE, etc.).
05What does the null coalescing operator ?? do?
What does the null coalescing operator ?? do?
It returns the right-hand value when the left-hand value is null, which is a short way to set defaults.
Integer limitSize = config.Max_Records__c ?? 200;It was added in a recent release, so mentioning it shows you keep up with Apex changes.
06How does the switch statement work in Apex?
How does the switch statement work in Apex?
switch on works with Integers, Longs, Strings, enums and sObject types. Each when can list several values, and when else is the default.
switch on opp.StageName {
when 'Closed Won' { handleWon(opp); }
when 'Closed Lost', 'Withdrawn' { handleLost(opp); }
when else { }
}07How do you create a custom exception?
How do you create a custom exception?
Create a class whose name ends with Exception and that extends Exception. Throw it with a message when business rules fail.
public class InvoiceException extends Exception {}
if (inv.Amount__c < 0) throw new InvoiceException('Amount cannot be negative');Custom exceptions make error handling clearer, because callers can catch your specific type.
08What are the access modifiers in Apex, and when do you use global?
What are the access modifiers in Apex, and when do you use global?
What the interviewer is checking: That you know the default is private, and that global is a long-term commitment, not just "more public".
Apex has four: private (only inside the class; the default for methods and variables), protected (the class and classes that extend it), public (any code in the same namespace) and global (any code anywhere, including other namespaces).
Use global only when code outside your namespace must call it: managed package APIs, @RestResource classes, and web services. Once a global method is released in a managed package you cannot remove or change its signature, so keep it to the minimum.
Common mistake: Making everything public or global "to be safe". It exposes internals and, in a package, cannot be undone.
09What is the difference between method overloading and overriding in Apex?
What is the difference between method overloading and overriding in Apex?
What the interviewer is checking: Whether you understand virtual, abstract and override, and can connect them to a real pattern such as a trigger handler.
Overloading means several methods in the same class with the same name but different parameters, for example calculate(Decimal amount) and calculate(Decimal amount, String currencyCode). Apex picks one at compile time from the arguments.
Overriding means a child class replaces a parent method with the same signature. The parent method must be virtual or abstract, and the child must use the override keyword. Apex picks the version at run time from the actual object type, which is how a trigger framework lets each handler supply its own beforeInsert().
Common mistake: Forgetting that Apex methods are not overridable by default: without virtual or abstract on the parent, override fails to compile.
10Which String methods do you use most in Apex?
Which String methods do you use most in Apex?
What the interviewer is checking: Practical fluency, and especially whether you know that == on strings ignores case.
The ones that come up in real code:
String.isBlank(s)andisNotBlank: null-safe checks for empty or whitespace-only text. Prefer them tos == ''.split,join,contains,startsWith,substringBeforeandsubstringAfterLastfor parsing values such as an Id from a URL.toLowerCaseandequalsIgnoreCasefor comparisons; Apex==on strings is already case-insensitive,equals()is not.String.formatandString.jointo build messages;String.escapeSingleQuotesfor dynamic SOQL.abbreviate(n)to fit long text into a field limit before DML.
Common mistake: Calling a method on a null String. Use the static isBlank or check for null first.
11What is the difference between static and instance methods?
What is the difference between static and instance methods?
Static methods belong to the class itself, not an instance. They're called using the class name (MyClass.myMethod()) and can only access static variables. Instance methods belong to a specific object instance and can access both instance and static variables. Use static methods for utility functions that don't need instance state. Trigger handler classes typically use instance methods to maintain state during a transaction.
12How do you implement the Comparable interface?
How do you implement the Comparable interface?
Implement Comparable with a compareTo(Object other) method that returns a negative integer (less than), zero (equal), or positive integer (greater than). Use it for custom sorting of object lists with List.sort(). Example: sort Accounts by revenue descending. This is essential for custom ordering logic that SOQL ORDER BY can't handle, like sorting by a calculated value or multiple criteria with complex logic.
13What is the difference between transient and non-transient variables?
What is the difference between transient and non-transient variables?
The transient keyword is used in Visualforce controllers to exclude a variable from the view state. Transient variables are not serialized; they reduce view state size but lose their values between server round-trips. Use transient for large data sets displayed on the page but not needed in subsequent requests. In non-VF contexts, transient has no effect. For LWC, this concept doesn't apply as there's no view state: data is managed client-side.
14How do you use the JSON class in Apex?
How do you use the JSON class in Apex?
JSON.serialize(object) converts an Apex object to a JSON string. JSON.deserialize(jsonString, Type.class) converts JSON to an Apex object. JSON.deserializeUntyped(jsonString) returns a Map<String, Object> for dynamic parsing. Use JSONGenerator for building complex JSON manually. Use JSONParser for streaming large JSON payloads. Common pattern: create wrapper classes that mirror the JSON structure, then deserialize directly into them. Handle null values and missing fields gracefully.
15How do you get field information dynamically with Schema describe?
How do you get field information dynamically with Schema describe?
Use Schema.SObjectType and DescribeFieldResult to read labels, types, picklist values and permissions at runtime.
Schema.DescribeFieldResult f = Account.Industry.getDescribe();
for (Schema.PicklistEntry pe : f.getPicklistValues()) System.debug(pe.getLabel());
Boolean canEdit = f.isUpdateable();Describe calls are fast now, but avoid calling Schema.getGlobalDescribe() in loops.
16How long do static variables live in Apex?
How long do static variables live in Apex?
For one transaction. They are shared across all code in that transaction, including triggers that fire again, which is why a static Set of processed IDs works for recursion control.
They are not shared between users or transactions, and they reset between Batch Apex executions.
DML, SOQL and exceptions
17How does Apex handle exceptions?
How does Apex handle exceptions?
Apex uses try-catch-finally blocks similar to Java. Common exception types: DmlException, QueryException, NullPointerException, and CalloutException. Best practices: catch specific exceptions rather than the generic Exception class, log meaningful error messages, use custom exception classes for business logic errors, and never swallow exceptions silently. In triggers, uncaught exceptions roll back the entire transaction. In batch jobs, exceptions in execute() don't stop the overall job.
18What is the difference between Database.insert() and insert DML?
What is the difference between Database.insert() and insert DML?
The insert DML statement is all-or-nothing: if one record fails, the entire operation rolls back. Database.insert() accepts an allOrNone parameter. Set it to false to allow partial success, where successful records are committed and failed records are returned with errors. Database methods return Database.SaveResult[] for analyzing individual record outcomes. Use Database methods when processing data from external sources where partial success is acceptable.
19How do you handle partial success in DML?
How do you handle partial success in DML?
Use Database.insert(records, false) (or update or upsert) so valid records are saved even if some fail. Then loop over the returned Database.SaveResult list and handle the errors.
for (Database.SaveResult sr : Database.insert(accs, false)) {
if (!sr.isSuccess()) {
for (Database.Error e : sr.getErrors()) System.debug(e.getStatusCode() + ': ' + e.getMessage());
}
}20What is upsert with an external ID, and why do integrations use it?
What is upsert with an external ID, and why do integrations use it?
What the interviewer is checking: Whether you design integrations to be safe to retry, which is what external IDs give you.
upsert inserts records that do not exist and updates those that do, matching on a field. By default it matches on the record Id, but integrations match on an External ID field, such as ERP_Id__c, because the source system does not know Salesforce Ids.
List<Account> accs = new List<Account>{ new Account(ERP_Id__c = 'C-1001', Name = 'Acme') };
Database.UpsertResult[] res = Database.upsert(accs, Account.ERP_Id__c, false);It makes loads safe to re-run: sending the same record twice updates it instead of creating a duplicate. Mark the external ID field Unique, and remember that duplicates inside the same list cause an error.
Common mistake: Using insert for data that may already exist, then fixing duplicates later.
21How do you prevent SOQL injection in dynamic queries?
How do you prevent SOQL injection in dynamic queries?
Never concatenate user input directly into SOQL strings. Solutions:
- Use bind variables: Database.query('SELECT Id FROM Account WHERE Name = :userInput').
- Use String.escapeSingleQuotes() to sanitize input.
- Use the SOQL WITH clause for additional filtering.
Best practice: prefer static SOQL over dynamic SOQL whenever possible. When dynamic SOQL is necessary, always sanitize inputs and validate field/object names against Schema.describe results.
22How do you write an efficient SOQL query for large data volumes?
How do you write an efficient SOQL query for large data volumes?
- Use indexed fields in WHERE clauses (Id, Name, RecordType, lookup fields, and custom indexed fields).
- Add selective filters that return less than 10-15% of total records.
- Limit fields in SELECT to only what you need.
- Use LIMIT clause when you don't need all results.
- Avoid using NOT, != or LIKE '%text' in filters as they prevent index usage.
- For large result sets, use FOR loops to process records in chunks of 200 rather than loading all into a list.
23What are Apex cursors?
What are Apex cursors?
Apex cursors let you query a very large result set once and then fetch it in chunks, moving forward and back, across several Queueable jobs. They are an alternative to Batch Apex when you need more control over how records are processed.
They are a newer feature, so check the current limits in the Apex Developer Guide before recommending them in a design.
Triggers
24What are trigger context variables?
What are trigger context variables?
Trigger context variables provide information about the current trigger execution. Trigger.new: list of new records (insert, update). Trigger.old: list of old records (update, delete). Trigger.newMap: map of new records by ID (after triggers, update). Trigger.oldMap: map of old records by ID (update, delete). Trigger.isInsert/isUpdate/isDelete/isUndelete: Boolean flags for operation type. Trigger.isBefore/isAfter: timing flags. Trigger.size: number of records. Use these for efficient trigger logic.
25How do you handle recursive trigger prevention with a Set?
How do you handle recursive trigger prevention with a Set?
Instead of a simple Boolean flag, use a static Set<Id> to track which specific record IDs have been processed. In the trigger, check if the current record's ID is in the Set. If not, add it and proceed with logic. This is more granular than a Boolean; it allows the trigger to process new records while preventing re-processing of already-handled records. Reset the Set between test methods to avoid test interference.
Asynchronous Apex
26Explain the Queueable interface and its advantages over @future.
Explain the Queueable interface and its advantages over @future.
Queueable Apex is more powerful than @future: it supports complex data types as parameters (not just primitives), allows chaining (one job enqueuing another), provides a job ID for monitoring, and supports higher governor limits. Use Queueable when you need to pass SObjects or collections to async methods, chain multiple async operations, or monitor job status. The main limitation: you can only chain one Queueable from another Queueable in production (unlimited in test context).
27How do you implement Batch Apex and when do you use it?
How do you implement Batch Apex and when do you use it?
Implement Database.Batchable<SObject> with three methods: start() returns the query or iterable, execute() processes each batch of records, and finish() handles post-processing. Use batch when processing 50K+ records that exceed synchronous limits. Set batch size (scope parameter) based on complexity: 200 is default, reduce for complex processing, increase for simple operations. Implement Database.Stateful to maintain state across batches. Use Database.AllowsCallouts for HTTP callouts.
28How do you implement Scheduled Apex?
How do you implement Scheduled Apex?
Implement the Schedulable interface with an execute(SchedulableContext sc) method. Schedule via System.schedule('Job Name', cronExpression, new MyScheduledClass()). Cron format: 'seconds minutes hours day month weekday year'. Common pattern: the scheduled class instantiates and executes a Batch job. Limitations: can only have 100 scheduled Apex jobs at once, and Schedulable context has reduced governor limits. Use for periodic data cleanup, report generation, or batch job orchestration.
29What is Database.Stateful in Batch Apex?
What is Database.Stateful in Batch Apex?
By default, each batch execution starts with fresh instance variables. Implementing Database.Stateful keeps instance variables between batches, for example to count processed records or collect errors and email them in finish().
Use it only when needed: the state is serialised between batches, which adds overhead.
30What is a Transaction Finalizer?
What is a Transaction Finalizer?
A Finalizer is a class implementing System.Finalizer, attached to a Queueable job with System.attachFinalizer(). It runs after the job finishes, even if the job failed with an uncatchable error such as a limit exception.
It is the standard way to log failures and retry Queueable jobs safely.
Sharing and security in Apex
31What is the difference between with sharing and without sharing?
What is the difference between with sharing and without sharing?
With sharing enforces the running user's sharing rules; they can only access records they have access to. Without sharing ignores sharing rules: the code accesses all records regardless of the user's permissions. Default behavior: if not specified, a class inherits the sharing context of its caller. Best practice: always specify sharing explicitly. Use with sharing for user-facing operations. Use without sharing sparingly, only when you genuinely need to bypass sharing (like system-level utilities).
32What is the difference between system mode and user mode in Apex?
What is the difference between system mode and user mode in Apex?
What the interviewer is checking: That you know with sharing covers records only, not field or object permissions, and how user mode closes that gap.
By default Apex runs in system mode: it ignores the running user's object and field permissions. Sharing (record access) is controlled separately by the class keywords with sharing, without sharing and inherited sharing.
User mode makes a query or DML respect the user's object permissions, field-level security and sharing, all at once:
List<Account> accs = [SELECT Name, AnnualRevenue FROM Account WITH USER_MODE];
Database.insert(records, AccessLevel.USER_MODE);Use user mode for anything a user triggers from the UI, such as an LWC controller. Keep system mode for trusted background work, such as a batch job that must see every record. WITH USER_MODE is the modern replacement for WITH SECURITY_ENFORCED, which only checked reads and stopped at the first inaccessible field.
Common mistake: Saying "my class is with sharing, so it is secure". Field-level security is still ignored unless you use user mode or stripInaccessible.
33What is Apex Managed Sharing (programmatic sharing)?
What is Apex Managed Sharing (programmatic sharing)?
Apex Managed Sharing lets you create sharing records programmatically using the __Share object. Each Share record specifies UserOrGroupId, AccessLevel (Read/Edit), and RowCause. Use it when standard sharing rules aren't flexible enough, for example, sharing records based on complex business logic that involves multiple criteria or external data. Share records created programmatically with a custom RowCause can only be deleted by code, not by admins.
Callouts and Platform Events
34Explain Platform Events and how to publish/subscribe in Apex.
Explain Platform Events and how to publish/subscribe in Apex.
Platform Events are event-driven messaging. Publish: EventBus.publish(new My_Event__e(Field__c = 'value')). Subscribe: create an Apex trigger on the event object (after insert). Key behaviors: published events are not rolled back even if the publishing transaction fails (use Publish After Commit for transactional behavior). Subscribers run in their own execution context with fresh governor limits. Use for decoupling processes, cross-system notifications, and logging. Monitor delivery with EventBusSubscriber.
35What is the Continuation class and when do you use it?
What is the Continuation class and when do you use it?
Continuation is for long-running callouts in Visualforce/LWC: up to 120 seconds vs the normal 10-second timeout for synchronous calls. It allows up to 3 parallel callouts. The pattern is asynchronous: start the callout, return the Continuation object, Salesforce parks the request, and when the callout completes, a callback method processes the response. Use for slow external APIs, large data retrieval, or when you need parallel external requests.
36How do you implement a retry mechanism for callouts?
How do you implement a retry mechanism for callouts?
Create a Queueable class that makes the callout and tracks retry count. On failure, check the attempt number against a maximum. If retries remain, enqueue a new instance with incremented count. Use exponential backoff: wait 1s, 2s, 4s between retries. Store retry metadata in a Custom Metadata Type for configuration. Log each attempt. Consider a dead letter pattern: after max retries, create an error record for manual review. Always make the operation idempotent.
Testing Apex
37What is the @testVisible annotation?
What is the @testVisible annotation?
@testVisible makes private or protected members accessible to test methods without changing their visibility in production code. Use it for private helper methods and variables you need to test or set up test state. Example: @testVisible private static Boolean skipValidation = false;; in tests, set it to true to bypass validation for setup. This is better than making methods public just for testing.
38What do Test.startTest() and Test.stopTest() do?
What do Test.startTest() and Test.stopTest() do?
Code between them gets a fresh set of governor limits, separate from your test setup. Test.stopTest() also forces asynchronous work (future, Queueable, Batch, scheduled jobs) started inside the block to run, so you can assert on the results right after.
Each test method can call them only once.
39What is the Assert class?
What is the Assert class?
The Assert class gives clearer test assertions than System.assertEquals: Assert.areEqual, Assert.isTrue, Assert.isNull, Assert.fail and others.
Always add a message as the last argument so a failing test explains itself.
40How do you handle callout mocking in test classes?
How do you handle callout mocking in test classes?
Implement HttpCalloutMock interface with a respond() method that returns a mock HttpResponse. Register it in your test with Test.setMock(HttpCalloutMock.class, new MockClass()). For multiple callouts, use MultiStaticResourceCalloutMock or implement logic in respond() based on the request endpoint. Use StaticResource for complex response bodies. Always test both success (200) and failure (400, 500) responses. Mock callouts execute synchronously in tests.
41When do you use System.runAs() in tests?
When do you use System.runAs() in tests?
To run code as a specific user, so you can test sharing and record access, and to avoid Mixed DML errors when the test creates users and business records.
Note that runAs does not enforce field-level security or object permissions on its own; use user-mode queries in the code under test for that.
Design and performance
42What are the best practices for writing Apex in a multi-tenant environment?
What are the best practices for writing Apex in a multi-tenant environment?
- Bulkify everything: process collections, not individual records.
- Minimize SOQL/DML: query and update in bulk outside loops.
- Use efficient data structures: Maps for lookups, Sets for uniqueness.
- Avoid hardcoding IDs: use Custom Metadata or describe calls.
- Handle errors gracefully: partial success patterns.
- Write thorough tests: positive, negative, bulk, and mixed scenarios.
- Use async processing for heavy operations.
- Monitor limits at runtime with the Limits class.
43How do you return a list of records with a wrapper class to LWC?
How do you return a list of records with a wrapper class to LWC?
Create an inner class with public properties marked @AuraEnabled, fill a list of it in an @AuraEnabled method and return the list. LWC receives it as plain JavaScript objects.
public class Row {
@AuraEnabled public String name;
@AuraEnabled public Decimal total;
}
@AuraEnabled(cacheable=true)
public static List<Row> getRows() { ... }Wrappers are useful when the UI needs data from several objects or calculated values.
44What is the Abstract class pattern in Apex?
What is the Abstract class pattern in Apex?
Abstract classes can't be instantiated: they serve as base classes with shared logic and abstract methods that subclasses must implement. Use for trigger frameworks: abstract TriggerHandler with beforeInsert(), afterUpdate() etc. Subclasses implement only the methods they need. Also used for service layers, batch job templates, and integration patterns. The key difference from interfaces: abstract classes can have implemented methods and state, while interfaces only define method signatures.
45What is Platform Cache and when should you use it?
What is Platform Cache and when should you use it?
Platform Cache stores data in memory for reuse, either per org (shared by all users) or per session. It suits data that is expensive to compute or fetch and changes rarely, such as exchange rates or configuration.
Cache is not guaranteed: always handle a cache miss by loading the data again.
Common Mistakes in Apex Interviews
Writing SOQL inside loops. This is the most common red flag. Always collect IDs first and query outside the loop. Interviewers actively look for this.
Not handling null values. Failing to check for null before accessing properties shows lack of production experience. Always guard against NullPointerException.
Ignoring sharing context. Not specifying 'with sharing' or 'without sharing' shows you don't think about security. Always be explicit.
Hardcoding IDs. Using hardcoded record IDs in code is a deployment hazard. Use Custom Metadata Types or describe calls instead.
Interviewer Follow-Up Patterns
In real Salesforce interviews, the first answer is rarely the last. Most interviewers chain follow-up questions to test depth. These are the patterns that come up again and again in 2026 panels:
- You explain bulkification → they ask "how would you handle 50,000 records: sync or async?"
- You mention triggers → expect "how do you avoid recursion in a multi-trigger org?"
- You bring up Queueable → they push with "how do you handle a chained job that fails halfway?"
- You answer about test classes → they ask about seeAllData=false, Test.startTest, and mock callouts.
- You describe SOQL → they want a selective query plan and indexed-field strategy.
Real Project Experience Signals
Strong candidates always mention one real-world example per answer. In real Salesforce projects, Apex is rarely written in isolation; it sits next to Flows, LWCs, and external systems. A few experience-grade lines you can borrow:
"In one enterprise rollout we replaced a 1,200-line trigger with a Trigger Handler framework: deployment time dropped by 40%."
"We hit CPU limits during peak Lead import, so we moved enrichment from a synchronous trigger to a Queueable chain: limits stopped failing instantly."
"For a banking client we used Database.Stateful in Batch Apex to roll up 2M+ transactions overnight without breaking heap."
Strengthen your preparation by exploring related question banks in the same topic cluster. Each guide covers a unique angle of apex interviews: pick the one closest to the role you are targeting.
Frequently Asked Questions about Apex Interviews
What level of Apex knowledge is expected in a 2026 interview?
For mid-level developer roles you should be fluent in collections, SOQL/SOSL, triggers with the trigger handler pattern, batch and queueable Apex, test classes with at least 75% coverage, and exception handling. Senior roles add asynchronous design patterns, Platform Events, Change Data Capture, and dynamic Apex.
How do I answer 'how would you optimize an Apex trigger' questions?
Lead with bulkification: never put SOQL or DML inside a loop. Then mention using a single trigger per object with a handler class, using Maps for related-record lookups, and using before-triggers for field updates to avoid extra DML. Finally, mention selective queries with custom indexes for large data volumes.
Should I memorize governor limits for an Apex interview?
Yes. At least the most-asked ones: 100 SOQL queries per transaction (synchronous), 150 DML statements, 50,000 records retrieved, 10MB heap size, and 10-second CPU time for synchronous Apex. You don't need exact numbers for every limit, but the headline numbers come up constantly.
How important are Apex test classes in interviews?
Very. Expect at least one question on test data setup with @testSetup, the difference between Test.startTest()/stopTest(), how to mock callouts with HttpCalloutMock, and why 75% coverage is a deployment minimum but not a quality goal. Many interviewers also ask about negative tests and assertion patterns.
Is Apex still relevant in the era of Flow and Agentforce?
Absolutely. Flow handles ~70% of automation use cases declaratively, but Apex remains essential for complex business logic, callouts, batch processing, and custom REST APIs. Agentforce actually increases Apex relevance because Invocable Apex methods are how you expose custom logic to AI agents.