Courseiva

CCNA Developer Fundamentals Questions

75 of 76 questions · Page 1/2 · Developer Fundamentals topic · Answers revealed

1
MCQeasy

What is the primary purpose of the Model-View-Controller (MVC) design pattern implementation in Lightning Web Components (LWC)?

A.To convert Apex triggers into asynchronous jobs
B.To bypass Salesforce governor limits automatically
C.To separate data, user interface, and application logic into distinct components
D.To enforce field-level security without writing code
AnswerC

MVC divides LWC code so the model holds data and business logic, the template renders the view, and the controller handles user interaction. This separation satisfies the requirement for distinct components, improving maintainability, testability and reuse across the application.

Why this answer

MVC separates application data (Model), user interface (View), and business logic/event handling (Controller) to promote modularity and maintainability.

2
Multi-Selecthard

Which THREE techniques help prevent hitting governor limits when writing SOQL queries in Apex? Choose 3 answers.

Select 3 answers
A.Omitting LIMIT clauses on large queries to ensure all records are fetched at once.
B.Filtering queries using indexed fields (such as Id, Name, or external IDs) where possible.
C.Querying records into lists rather than single sObject variables when multiple records match.
D.Using bind variables to pass collection criteria into SOQL WHERE clauses.
E.Placing SOQL queries inside helper methods called within loops.
AnswersB, C, D

Query optimisation through indexed fields directly addresses the requirement to prevent SOQL governor limits by drastically reducing database scan times. Standard fields like Id and Name, alongside custom indexed or external ID fields, allow the Salesforce query optimizer to bypass complete table scans and retrieve records via a B-tree lookup structure. This targeted retrieval consumes significantly fewer CPU time and database query resources, ensuring transactions execute well within strict multi-tenant resource boundaries.

Why this answer

Best practices include querying into collections, using bind variables, and filtering with indexed fields.

3
MCQhard

A developer is writing a trigger on the Contact object that needs to reference old field values during an update operation. In which trigger context variable are these previous values stored?

A.Trigger.new
B.Trigger.previousValues
C.Trigger.newMap
D.Trigger.old
AnswerD

`Trigger.old` is the correct context variable because it stores a collection of `Contact` sObjects representing the pre-update state of records during a DML update operation. This directly satisfies the requirement in the stem to reference old field values when executing a trigger on the `Contact` object. By providing access to the prior versions of records in bulk, it allows developers to compare previous field values against current values found in `Trigger.new` to evaluate changes before committing database transactions.

Why this answer

Trigger.old contains a list of sObject records prior to the update or delete operation.

4
Multi-Selectmedium

Which TWO statements about SOQL relationship queries are true? Choose 2 options.

Select 2 answers
A.SOQL supports traversing up to 10 levels of parent relationships.
B.Parent-to-child queries use dot notation on the parent object.
C.Child-to-parent queries require subqueries.
D.Child-to-parent queries use dot notation (e.g., Account.Name).
E.Parent-to-child queries use a subquery inside parentheses.
AnswersD, E

Child-to-parent queries in Salesforce Object Query Language utilise standard dot notation to traverse the data model from a child object to its related parent, successfully satisfying the requirement to identify the correct syntax for traversing relationships. By referencing the relationship name followed by the parent field (for example, `Account.Name` when querying Contacts), developers can retrieve fields from a single related parent record in a single query execution.

Why this answer

Parent-to-child queries use subqueries in parentheses, and child-to-parent queries use dot notation.

5
MCQhard

An application uses a SOSL search to find records across multiple objects. Which return type must be used to capture the results in Apex?

A.List<List<SObject>>
B.Map<String, List<SObject>>
C.SearchResult[]
D.List<SObject>
AnswerA

SOSL returns results grouped by object, so a single flat list cannot hold them. `List<List<SObject>>` preserves that per-object grouping, with each inner list holding matches for one searched object. This satisfies the stem's requirement to capture cross-object results from one SOSL query in Apex.

Why this answer

SOSL search queries return a List of Lists of SObjects (List<List<SObject>>), because a single search can return results across multiple different sObject types.

6
Multi-Selectmedium

A developer is building a custom Lightning Web Component and wants to communicate data from a child component up to its parent component. Which THREE steps are required? (Choose three.)

Select 3 answers
A.Dispatch the event using the this.dispatchEvent() method in the child.
B.Import the wire service adapter in the parent component.
C.Use the @api decorator on a parent property inside the child component.
D.Create a new CustomEvent in the child component's JavaScript file.
E.Add an event listener directive (e.g., onmyevent) to the child component tag in the parent HTML template.
AnswersA, D, E

Custom events in Lightning Web Components are dispatched from the child component using the standard DOM `CustomEvent` API wrapped in the component's `this.dispatchEvent()` method. This fulfills the communication requirement specified in the stem—passing data upward from a child to a parent component—by bubbling the event up the DOM tree where a parent template can listen for it using an event listener directive.

Why this answer

To send data from a child LWC up to its parent, the child must first create the event object with the CustomEvent constructor, as in option D, because CustomEvent carries the payload in its detail property and defines the event name the parent will listen for. Option A is correct because the child must actually fire that event by calling this.dispatchEvent(event), which is the only way an LWC event is propagated to the parent's DOM listener. Option E is correct because the parent must register a listener on the child's tag in its HTML template using the on<eventname> directive (for example onmyevent), which binds the handler that receives the event and its detail data.

Option B is incorrect because wire service adapters are used for reading Salesforce data, not for child-to-parent event communication, and no wire adapter is needed here. Option C is incorrect because @api exposes a public property for the parent to pass data down into the child, which is the opposite direction of the required child-to-parent flow.

7
MCQhard

An Apex trigger needs to prevent records from being saved if a specific validation condition fails. How should the developer reject the DML operation on a specific record?

A.record.addError('Validation failed.');
B.Trigger.rollback();
C.ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error'));
D.throw new ValidationException('Error');
AnswerA

addError() on an SObject instance marks that specific record as failed and blocks its DML while allowing other records in the transaction to save. This satisfies the requirement to reject only the offending record rather than throwing an exception that rolls back the entire operation.

Why this answer

Adding an error message to a record sObject in Trigger.new (e.g., record.addError('Message')) prevents that record from saving and adds an error to the UI/transaction.

8
Multi-Selecteasy

Which TWO methods are used to inspect sObject field metadata dynamically in Apex? Choose 2 options.

Select 2 answers
A.Schema.getGlobalDescribe()
B.System.describeFields()
C.Object.inspect()
D.Database.getMetadata()
E.SObjectType.getDescribe()
AnswersA, E

`Schema.getGlobalDescribe()` successfully satisfies the requirement to inspect sObject field metadata dynamically by returning a map of all sObject tokens keyed by their API names across the entire organization. Developers can iterate through this dynamic map at runtime to programmatically resolve specific object types without hardcoding dependencies, which is essential for generic utility classes and managed packages that must adapt to custom customer schemas.

Why this answer

SObjectType.getDescribe() and Schema.getGlobalDescribe() are used for inspecting schema metadata.

9
MCQhard

A developer is writing a batch Apex class. During the execute method, a record fails validation. The developer wants to ensure that successfully processed records in the same batch are committed while failing records are logged without aborting the entire batch. How should the DML be performed?

A.try-catch block around a standard insert statement
B.Database.upsert(records, true)
C.Database.insert(records, false)
D.Standard insert statement (e.g., insert records;)
AnswerC

Using `Database.insert(records, false)` enables partial processing by passing `false` as the second parameter for the allOrNone argument. This satisfies the strict constraint that successfully processed records must be committed while failing records do not abort the entire batch. Instead of rolling back the entire transaction upon encountering a validation error, the runtime flags the specific failed records in the resulting `Database.SaveResult` array, allowing successful database operations to persist.

Why this answer

Using Database.insert(records, false) performs partial DML success, allowing valid records to commit while returning an array of save results for error handling.

10
MCQmedium

A developer needs to find all records across multiple objects (Contact, Lead, and Account) that contain the exact phrase 'Acme Corp'. Which feature should be used?

A.Database.query() with dynamic bindings
B.SOQL query with multiple WHERE clauses
C.SOSL FIND clause
D.Global Search API via REST
AnswerC

Salesforce Object Search Language (SOSL) satisfies the requirement to query multiple distinct objects simultaneously using the `FIND` clause to locate the exact phrase 'Acme Corp' across the specified fields of Contact, Lead, and Account records. Unlike SOQL, which is restricted to querying a single sObject at a time (unless utilizing parent-to-child relationships), SOSL is specifically engineered for text-based, multi-object searches executed against an inverted index, making it the correct architectural choice for cross-object retrieval.

Why this answer

SOSL (Salesforce Object Search Language) is designed for text searches across multiple objects simultaneously.

11
Multi-Selecthard

Which THREE best practices should a developer follow when implementing CRUD and FLS checks in Apex? Choose 3 answers.

Select 3 answers
A.Rely solely on 'with sharing' keywords to handle field-level security checks.
B.Check sObject createability before performing insert DML operations.
C.Disable all triggers when performing security checks.
D.Check object updatability before committing updates to the database.
E.Use Schema describe methods to verify field accessibility before querying.
AnswersB, D, E

Ensuring the application respects CRUD security requires developers to programmatically verify user permissions prior to executing database actions. Specifically, checking `sObject` createability via the `Schema.sObjectType.MyObject__s.isCreateable()` method satisfies the createability validation constraint for CRUD enforcement before performing an `insert` DML operation. This proactive validation prevents runtime exceptions and maintains data governance standards by stopping unauthorised record creation attempts at the application tier.

Why this answer

Developers should check isAccessible, isCreateable, and isUpdateable using describe results before querying or saving data.

12
MCQhard

A developer is writing code that processes untrusted data and wants to automatically strip fields and relationships that the current user cannot access, without throwing an exception. Which feature should be used?

A.Security.stripInaccessible()
B.Database.insert(records, AccessType.ENFORCE_ACCESSIBLE)
C.Approval.lock()
D.Schema.sObjectType.fields.isAccessible()
AnswerA

`Security.stripInaccessible()` satisfies the requirement to automatically remove fields and relationships that the current user lacks read, create, or update permissions for, without throwing an exception. By using the `AccessType` enum (such as `AccessType.READABLE`), the developer can pass lists of sObjects and have the runtime strip inaccessible fields in-place. This approach avoids explicit conditional permission checks and prevents the runtime exceptions that standard database operations or `ApexPages.addMessage()` patterns would otherwise trigger when encountering restricted data.

Why this answer

The Security.stripInaccessible() method strips fields and SObjects that the user lacks permission to read or create/update, avoiding runtime security exceptions.

13
MCQeasy

Which Apex data type should a developer use to represent a precise geographic location with latitude and longitude coordinates?

A.Coordinate
B.Location
C.Address
D.GeoPoint
AnswerB

The built-in Apex `Location` data type directly satisfies the requirement for representing a precise geographic location with latitude and longitude coordinates. Unlike generic numeric or string variables, `Location` natively stores spatial data using compound fields, allowing developers to perform built-in distance calculations such as `EucDist` or `toMiles`. It ensures type safety and seamless integration with Salesforce geolocation fields and SOQL spatial functions like `DISTANCE()` and `GEOLOCATION()`, fulfilling the exact criteria specified in the stem.

Why this answer

The Location primitive data type in Apex is designed specifically to represent geographic locations with latitude and longitude.

14
MCQeasy

Which collection type stores elements as key-value pairs in Apex?

A.Set
B.Array
C.List
D.Map
AnswerD

A Map collection in Apex successfully satisfies the requirement from the stem to store elements as key-value pairs by associating unique keys with corresponding values. Unlike lists or sets that store individual items sequentially or uniquely, a Map provides a direct hashing mechanism where each distinct key maps to a single value, allowing developers to efficiently retrieve, update, or remove data using the specified key reference.

Why this answer

A Map stores key-value pairs where each unique key maps to a single value.

15
MCQhard

An Apex trigger executes during a bulk insert of 300 records. To adhere to best practices regarding governor limits and bulkification, how should SOQL queries be written?

A.Query inside a for-loop iterating over Trigger.new
B.Query each record individually using Limits.getQueries() checks
C.Use an asynchronous future method for every individual record
D.Query once outside the loop using a collection of IDs from Trigger.new
AnswerD

Collecting IDs from Trigger.new and issuing one SOQL query before the loop keeps the query inside governor limits regardless of the 300-record batch size. This satisfies the bulkification requirement by avoiding a query per record.

Why this answer

Queries must be written using bulkified collections, querying once outside of loops using bind variables for all records in Trigger.new.

16
MCQmedium

A developer is writing a SOQL query to find accounts where the billing country starts with 'United'. Which operator should be used?

A.LIKE 'United%'
B.MATCHES
C.STARTS_WITH
D.INCLUDES
AnswerA

The `LIKE` operator combined with the wildcard character `%` satisfies the stem's requirement to locate accounts where the billing country field begins with a specific string. In Salesforce Object Query Language, the wildcard `%` represents zero or more characters, allowing the query engine to match any billing country value starting with the exact sequence 'United' followed by subsequent characters, such as 'United Kingdom' or 'United States'.

Why this answer

The LIKE operator is used in SOQL for wildcard matching, using '%' as the wildcard character.

17
MCQeasy

Which SOQL aggregate function should a developer use to count the exact number of rows returned by a query without retrieving the records into memory?

A.COUNT()
B.TOTAL()
C.SUM()
D.SIZE()
AnswerA

The `COUNT()` aggregate function evaluates the exact number of records matching the query criteria directly within the database layer, satisfying the constraint of not retrieving the records into memory. Unlike standard queries that instantiate record objects within the heap, this function returns a single integer value representing the total row count. This mechanism significantly reduces heap size consumption and prevents governor limit exceptions when developers need to verify record volumes efficiently.

Why this answer

The COUNT() function returns the number of rows matching the query criteria efficiently as an integer.

18
Multi-Selecteasy

Which TWO methods are available on the Database class for performing DML operations with partial success capability? Choose 2 options.

Select 2 answers
A.Database.save()
B.Database.commit()
C.Database.persist()
D.Database.update()
E.Database.insert()
AnswersD, E

`Database.update()` directly satisfies the requirement for partial success capability by accepting an optional `allOrNone` boolean parameter, which defaults to true. When explicitly set to false, this method processes records independently, allowing valid updates to commit to the database even if other records fail validation or trigger runtime exceptions. This contrasts with standard DML statements like `update`, which enforce an all-or-nothing execution model that rolls back the entire transaction upon encountering a single error.

Why this answer

Database.insert() and Database.update() accept an allOrNone boolean parameter allowing partial success.

19
MCQmedium

A developer needs to dynamically instantiate an sObject type based on a string variable representing the object name (e.g., 'Account'). Which method should be used?

A.Schema.getGlobalDescribe().get('Account').newSObject()
B.Type.forName('Account').newInstance()
C.Database.load('Account')
D.SObject.createInstance('Account')
AnswerA

getGlobalDescribe() returns a map of all sObject types keyed by API name, and newSObject() on the resulting token instantiates the concrete type from the string. This satisfies the stem's requirement for dynamic instantiation without hard-coded class references.

Why this answer

Schema.getGlobalDescribe().get('Account').newSObject() allows dynamic sObject creation from a string object name.

20
MCQmedium

A developer needs to ensure that an Apex class respects organization-wide defaults, role hierarchies, and sharing rules when querying custom objects. Which keyword should be added to the class definition?

A.enforce sharing
B.with sharing
C.without sharing
D.inherited sharing
AnswerB

Adding `with sharing` to the Apex class definition enforces record-level security by ensuring that Salesforce applies organization-wide defaults, role hierarchies, and sharing rules during SOQL queries on custom objects. By default, Apex runs in system mode and ignores user-based sharing settings, which would bypass these constraints. Declaring the class `with sharing` forces the execution context to respect the requesting user's specific record permissions, directly satisfying the requirement to restrict data visibility according to the defined sharing model.

Why this answer

The with sharing keyword enforces sharing rules of the current user, while without sharing runs in system mode.

21
Multi-Selectmedium

Which TWO features are characteristics of SOSL (Salesforce Object Search Language) queries? Choose 2 answers.

Select 2 answers
A.SOSL returns a single flat List of SObjects.
B.SOSL queries can update existing records directly.
C.SOSL queries are limited to a maximum of 10 records per search.
D.SOSL can search across multiple sObjects and fields in a single query.
E.SOSL tokenizes search terms to perform optimized text matching.
AnswersD, E

Salesforce Object Search Language (SOSL) is specifically designed to perform text-based searches across multiple standard and custom objects simultaneously through a single programmatic request. This capability directly satisfies the stem constraint requiring a query mechanism that can search across multiple sObjects and fields concurrently. Unlike SOQL, which retrieves records from a single object at a time using relational filters, a single SOSL `FIND` query tokenises search terms and indexes text fields across diverse, unrelated objects like Accounts, Contacts, and Leads within one execution.

Why this answer

SOSL searches text across multiple objects and fields simultaneously and can tokenize words for matching.

22
MCQeasy

Which Apex data type is best suited for storing monetary amounts with high precision?

A.Decimal
B.Double
C.String
D.Integer
AnswerA

Monetary amounts and calculations requiring strict precision must use the Decimal primitive data type to prevent the rounding errors inherent in binary floating-point representations. Unlike Double, which uses base-two approximation and introduces inaccuracies during arithmetic operations, Decimal operates using arbitrary-precision base-ten arithmetic. This exact decimal representation satisfies the high precision constraint specified in the stem, ensuring financial transactions and currency values calculate accurately without accumulating cumulative rounding discrepancies.

Why this answer

The Decimal data type is used for currency and precise numerical calculations in Apex.

23
MCQeasy

What is the correct file extension for an Apex class created in Salesforce DX?

A..apex
B..controller
C..cls
D..trigger
AnswerC

Apex classes in Salesforce DX require the `.cls` extension because the Salesforce CLI and underlying metadata API strictly enforce this suffix to identify and parse server-side controller logic during source synchronisation and deployment. This specific file extension directly satisfies the format constraint specified in the stem for source-tracked enterprise development artifacts.

Why this answer

Apex class files use the .cls extension, accompanied by a .cls-meta.xml metadata file.

24
MCQeasy

A developer wants to retrieve up to 5 recently viewed records of any object type using SOSL. Which SOSL clause specifies the maximum number of records to return?

A.TOP 5
B.MAX 5
C.LIMIT 5
D.ROWS 5
AnswerC

The `LIMIT` clause directly satisfies the stem constraint requiring the retrieval of up to 5 records by capping the total number of search result rows returned by the SOSL query. While SOQL handles record limits natively, appending `LIMIT 5` to a SOSL query ensures that the Salesforce search engine restricts the output size across the specified objects, optimising data transfer and processing when developers only require a subset of recently viewed items.

Why this answer

SOSL search results can be limited using the LIMIT clause at the end of the query statement.

25
MCQmedium

A developer writes a SOQL query to aggregate total opportunity amounts grouped by stage name. Which SOQL clause is required?

A.HAVING BY
B.GROUP BY
C.AGGREGATE BY
D.ORDER BY
AnswerB

Aggregating data across specific categories requires the `GROUP BY` clause to collapse multiple records into distinct groupings based on the specified field. In this scenario, the requirement to group opportunity amounts by their stage name directly satisfies the condition for using `GROUP BY`, as aggregate functions like `SUM()` cannot evaluate categorical fields without a designated grouping mechanism to define the summary boundaries.

Why this answer

Aggregate queries in SOQL require the GROUP BY clause when using functions like SUM(), COUNT(), or AVG().

26
Multi-Selectmedium

Which TWO data types can be used as keys in an Apex Map? Choose 2 answers.

Select 2 answers
A.Blob
B.Id
C.List<String>
D.SObject
E.String
AnswersB, E

Salesforce Record IDs satisfy the requirement that map keys must have a distinct hash code and support deterministic equality comparisons. Because the `Id` data type primitive is immutable, uniquely generated per record, and implements the necessary hashing algorithms natively within the Apex runtime, it functions reliably as a collection key. This ensures that lookups and insertions operate in constant time complexity without risking hash collisions or state mutations that would otherwise invalidate the map's internal index structure.

Why this answer

Primitive data types like String, ID, and Integer can be used as map keys in Apex.

27
Multi-Selectmedium

A developer is writing an Apex trigger and needs to optimize performance and prevent governor limit violations. Which TWO practices should the developer follow? (Choose two.)

Select 2 answers
A.Place DML statements inside 'for' loops to ensure immediate database commits.
B.Use the 'webservice' keyword on helper methods called by triggers.
C.Execute a separate SOQL query for every single record in Trigger.new.
D.Use trigger context variables like Trigger.new to process records in bulk.
E.Perform SOQL queries and DML operations outside of loops.
AnswersD, E

Using trigger context variables such as `Trigger.new` enables bulkified processing, which directly satisfies the requirement to prevent governor limit violations and optimise performance. Apex triggers execute once per batch of up to 200 records rather than per individual record. Accessing collections of records via these context variables ensures that SOQL queries and DML operations can be performed on entire lists simultaneously. This avoids hitting strict per-transaction limits, such as the maximum of 100 SOQL queries, regardless of whether a user updates a single record or thousands via a data load.

Why this answer

Option D is correct because Apex triggers must be bulkified: using trigger context variables such as Trigger.new lets the trigger process all records in a single invocation rather than one at a time, which conserves governor limits (e.g., the 100 SOQL queries and 150 DML statements per transaction). Option E is correct because moving SOQL queries and DML operations outside of loops ensures they execute once for the entire collection of records, avoiding the limit on queries/statements that would be exhausted by per-record execution inside a loop. Option A is wrong because placing DML inside a for loop causes one DML statement per iteration, quickly hitting the 150 DML statement governor limit and degrading performance.

Option B is wrong because the webservice keyword merely exposes a method for external web service callouts and does nothing to optimize trigger performance or prevent governor limit violations. Option C is wrong because issuing a separate SOQL query for each record in Trigger.new is the classic anti-pattern that exhausts the 100 synchronous SOQL query limit instead of bulkifying the query.

28
MCQeasy

A developer wants to define a constant value in an Apex class that can be accessed globally without instantiating the class. Which combination of keywords should be used?

A.protected static
B.public static final
C.private volatile
D.global transient
AnswerB

`public static final` satisfies both constraints: `static` binds the field to the class rather than an instance, so no object is needed, while `final` locks the value after assignment. `public` exposes it globally across the codebase. This combination is the standard Apex idiom for class-level constants.

Why this answer

Constants in Apex are defined using the 'static' and 'final' keywords to ensure they belong to the class and cannot be modified.

29
Multi-Selectmedium

Which TWO statements are true regarding the behavior of Apex triggers and context variables? Choose 2 answers.

Select 2 answers
A.Trigger.old is available in update and delete triggers.
B.Trigger.new is available in insert, update, and undelete triggers.
C.Trigger.old is available in insert and update triggers.
D.Trigger.new records are always read-only in before triggers.
E.Trigger.newMap is available in before insert triggers.
AnswersA, B

`Trigger.old` provides a read-only list of the previous versions of sObject records, which is essential for comparing field values before a database modification occurs. This context variable is accessible exclusively during update and delete operations because these events involve existing records that possess prior state data. Consequently, this satisfies the requirement to identify valid trigger context variables, as `Trigger.old` is unavailable during insert operations where no previous record state exists to reference.

Why this answer

Option A is correct because Trigger.old holds the previous versions of the records and is populated in update triggers (the old values before the change) and in delete triggers (the records being deleted), so it is available in both update and delete contexts. Option B is correct because Trigger.new holds the new versions of the records and is populated in insert triggers (records being created), update triggers (records with their new values), and undelete triggers (records being restored), making it available in all three contexts. Option C is wrong because Trigger.old is not available in insert triggers, since there are no prior versions of records that do not yet exist.

Option D is wrong because Trigger.new records are read-only only in after triggers; in before triggers they are writable and can be modified to change what is saved. Option E is wrong because Trigger.newMap is not available in before insert triggers, since the records have no IDs yet and the map is keyed by record ID.

30
Multi-Selecteasy

Which THREE collections are available in Apex? (Choose three.)

Select 3 answers
A.Queue
B.Set
C.Table
D.List
E.Map
AnswersB, D, E

A Set is a fundamental collection type in Apex that satisfies the requirement for storing unordered, unique elements. Unlike Lists, which permit duplicate entries and maintain a specific index-based order, a Set enforces data integrity by ensuring that no two elements share the same value. This mechanism makes it the optimal choice for scenarios where you must eliminate redundancies within a dataset, providing efficient methods to verify the existence of specific items while maintaining high performance during data processing tasks.

Why this answer

Apex provides three built-in collection types: List, Set, and Map.

31
MCQhard

An Apex trigger needs to prevent duplicate records from being inserted based on a custom external ID field. Which approach should the developer take to optimize query performance and respect governor limits?

A.Use Database.upsert with strict mode enabled inside the trigger loop.
B.Query the database inside a for loop for every record in Trigger.new.
C.Collect the external ID values into a Set, query once outside the loop, and use a Map for validation.
D.Use an asynchronous @future method to validate duplicates after insert.
AnswerC

Collecting external ID values into a Set allows for a single SOQL query executed outside the trigger loop, which directly satisfies the requirement to respect governor limits by avoiding the "too many SOQL queries" error. By mapping these retrieved records, the developer can perform constant-time lookups to validate duplicates efficiently. This approach ensures optimal performance when processing bulk data, as it minimises database round-trips and prevents the performance degradation associated with nested queries during high-volume record ingestion.

Why this answer

Collecting field values into a Set, querying existing records matching that Set in a single query outside of loops, and comparing in memory is the bulkified approach.

32
Multi-Selecthard

Which THREE factors can cause an Apex CPU time limit exception in a synchronous transaction? Choose 3 answers.

Select 3 answers
A.Executing nested loops over large collections of sObjects.
B.Running complex string manipulations or regular expression matching on large text bodies.
C.Invoking too many SOQL queries within the 100 query limit.
D.Exceeding the total number of allowed DML statements.
E.Executing heavy calculations inside triggers processing large bulk record batches.
AnswersA, B, E

Executing nested loops over large collections of sObjects directly contributes to the synchronous Apex CPU time limit exception by exponentially increasing the number of programmatic iterations within a single transaction. As the outer loop iterates over each record, the inner loop processes the entire collection again, resulting in an algorithmic time complexity of $O(n^2)$. This heavy computational burden exhausts the strict 10-second CPU time allocation enforced by the Salesforce multi-tenant platform for synchronous executions.

Why this answer

Heavy loops, complex triggers, inefficient nested queries or collections processing, and excessive regex or string manipulations contribute to CPU time exhaustion.

33
MCQmedium

A developer needs to assign a default value to a custom picklist field via Apex when creating a Lead record. What data type should be assigned to the picklist field in Apex?

A.String
B.Boolean
C.PicklistEntry
D.Integer
AnswerA

Assigning a `String` value to a custom picklist field in Apex satisfies the requirement because the Salesforce Schema treats picklist values as text literals during DML operations. When instantiating a new Lead record, the developer must pass the API name of the desired picklist value as a `String` to the field variable. This mechanism ensures the platform validates the input against the defined picklist metadata, successfully setting the default value without requiring complex object mapping or external authentication protocols like Microsoft Entra ID.

Why this answer

Picklist fields in Salesforce are represented as Strings in Apex when assigned or retrieved via sObjects.

34
Multi-Selecthard

Which THREE tools or contexts can be used to execute Anonymous Apex code? Choose 3 options.

Select 3 answers
A.Salesforce CLI (sf apex run)
B.Standard Page Layout Editor
C.Developer Console
D.Salesforce Extensions for Visual Studio Code
E.Lightning App Builder
AnswersA, C, D

The Salesforce CLI command sf apex run executes Anonymous Apex directly against an org from the terminal, supporting scripted and CI-friendly execution. This satisfies the requirement for a command-line context capable of running Anonymous Apex.

Why this answer

Salesforce CLI (option A) can execute Anonymous Apex via the `sf apex run` command (or the older `sfdx force:apex:execute`), which sends the Apex source to the Tooling API's executeAnonymous endpoint and returns the debug log and compile/run results. The Developer Console (option C) includes an Execute Anonymous window (Debug > Open Execute Anonymous Window) that compiles and runs arbitrary Apex in the current org and shows the resulting log. Salesforce Extensions for Visual Studio Code (option D) provide an "SFDX: Execute Anonymous Apex with Editor Contents" command that runs the active Apex file against an authorized org through the same executeAnonymous mechanism.

The Standard Page Layout Editor (option B) only arranges fields, buttons, and related lists on record pages and cannot run code, and Lightning App Builder (option E) is a declarative drag-and-drop tool for composing Lightning pages and components, not for executing Apex.

35
MCQeasy

A developer needs to store a collection of Account IDs where duplicates are automatically prevented and lookups are extremely fast. Which collection type should the developer use?

A.Map<Id, Id>
B.Queue<Id>
C.List<Id>
D.Set<Id>
AnswerD

A `Set<Id>` collection inherently enforces uniqueness by design, ensuring that duplicate Account IDs cannot be stored, which satisfies the requirement to prevent duplicates automatically. Furthermore, Sets in Apex utilise a hash-based implementation, providing constant-time complexity for lookups. This mechanism allows the developer to verify the existence of an ID with exceptional efficiency, far outperforming the linear search required by a List. This makes the Set the optimal structure for managing unique identifiers when rapid retrieval is prioritised.

Why this answer

Sets in Apex store unique elements and provide very fast lookups by value using methods like contains().

36
Multi-Selecthard

Which THREE operations can cause an automatic roll back of an entire Apex transaction? Choose 3 options.

Select 3 answers
A.Catching a DmlException inside a try-catch block.
B.Executing Database.insert(records, false) with partial failure.
C.Exceeding a governor limit such as SOQL query count.
D.A DML failure when allOrNone defaults to true (or standard DML syntax).
E.An unhandled exception occurring anywhere in the execution stack.
AnswersC, D, E

Exceeding a governor limit, such as the maximum number of SOQL queries allowed, triggers an unhandled exception that forces the Salesforce platform to abort the execution context. Because Apex transactions are atomic, the platform automatically rolls back all database changes performed during the request to maintain data integrity. This mechanism ensures that partial updates do not persist when a runtime governor limit is breached, satisfying the requirement for an automatic rollback within the transaction lifecycle.

Why this answer

Option C is correct because exceeding a governor limit (such as the SOQL query count) throws a runtime exception that cannot be caught, and the platform rolls back the entire Apex transaction. Option D is correct because standard DML statements (and Database methods with allOrNone set to true) throw a DmlException on failure, and if that exception is unhandled it aborts and rolls back the whole transaction. Option E is correct because any unhandled exception propagating up the execution stack terminates the transaction and triggers an automatic rollback of all DML performed in it.

Option A is not correct because catching a DmlException in a try-catch block lets execution continue, so the transaction is not automatically rolled back. Option B is not correct because Database.insert(records, false) uses allOrNone=false, allowing partial success without rolling back the entire transaction.

37
MCQmedium

A developer needs to convert a JSON string representing a list of Account objects into an actual Apex List of Accounts. Which method should be used?

A.JSON.deserialize(jsonString, List<Account>.class)
B.String.valueOf(jsonString)
C.JSON.serialize()
D.JSON.parse()
AnswerA

`JSON.deserialize` accepts a target type as its second argument, allowing the developer to map a JSON string directly into a strongly-typed Apex collection. By passing `List<Account>.class`, the method instructs the serialisation engine to instantiate the appropriate list structure and populate it with Account objects. This mechanism satisfies the requirement to convert a raw string into a functional Apex List, ensuring type safety and immediate access to object fields without manual parsing or complex type casting.

Why this answer

JSON.deserialize() or JSON.deserializeUntyped() are used to parse JSON, and JSON.deserialize(jsonString, TargetType.class) deserializes into strongly typed objects.

38
MCQeasy

A developer needs to check if a specific key exists in a Map<String, Decimal> before retrieving its value. Which Map method should be used?

A.containsKey()
B.hasKey()
C.contains()
D.exists()
AnswerA

The `containsKey()` method provides a boolean check against the map’s internal hash structure, returning true if the specified key is present. This mechanism directly satisfies the requirement to verify the existence of a key before retrieval, which prevents the developer from inadvertently triggering a null pointer exception or receiving an unexpected null value when accessing the map. By confirming the key's presence first, the code ensures robust data handling and avoids runtime errors during the subsequent value lookup process.

Why this answer

The containsKey() method checks whether a specified key exists in a Map instance.

39
MCQhard

An enterprise application requires Apex code to check whether the current user has read access to a specific custom field before displaying it in a custom Lightning Web Component. What is the most appropriate class to use?

A.System.Security
B.Schema.DescribeFieldResult
C.UserInfo
D.ApexPages.StandardController
AnswerB

`Schema.DescribeFieldResult` provides the `isAccessible()` method, which directly evaluates the current user's field-level security permissions for a specific custom field. By invoking this method before rendering data in a Lightning Web Component, developers ensure that the application adheres to the principle of least privilege. This approach satisfies the requirement to verify read access programmatically, preventing unauthorised data exposure that could occur if the component relied solely on UI-level visibility without backend validation.

Why this answer

The Schema.DescribeFieldResult class provides methods like isAccessible() to check Field-Level Security (FLS) dynamically.

40
MCQeasy

Which tool or feature in Salesforce Developer Console allows a developer to inspect debug logs and filter them by category and level?

A.Checkpoints
B.Log Inspector
C.Query Editor
D.Anonymous Apex
AnswerB

The Log Inspector provides a dedicated interface within the Developer Console specifically designed to parse and visualise complex debug logs. By offering granular controls for filtering entries based on both event categories and severity levels, it directly satisfies the requirement to inspect and refine log data. This tool enables developers to isolate specific execution paths efficiently, ensuring that they can practise effective debugging by stripping away irrelevant system noise to focus solely on the pertinent diagnostic information required for troubleshooting.

Why this answer

The Logs tab in the Developer Console displays execution logs, and Log Inspector provides detailed analysis tools.

41
MCQeasy

What is the maximum number of SOQL queries that can be issued in a single synchronous Apex transaction?

A.50
B.200
C.100
D.500
AnswerC

Salesforce enforces a strict governor limit of 100 SOQL queries per synchronous Apex transaction to ensure multi-tenant resource fairness. This constraint prevents any single process from monopolising database resources, which would otherwise degrade performance for other organisations sharing the same infrastructure. By restricting the total number of queries, the platform maintains consistent execution times and system stability. Developers must therefore optimise their code to batch data retrieval or utilise collections to remain within this defined threshold during their application logic.

Why this answer

The synchronous governor limit for SOQL queries is 100 queries per transaction.

42
MCQhard

An Apex trigger invokes a helper method that performs a DML operation, but the developer wants to establish a rollback point so that prior changes can be reverted if a subsequent error occurs. Which feature should be used?

A.Approval.lock()
B.System.createCheckpoint()
C.Database.Savepoint sp = Database.setSavepoint();
D.Database.beginTransaction()
AnswerC

`Database.setSavepoint()` creates a specific point in the database transaction, allowing a developer to revert partial DML operations if a subsequent error occurs. By invoking this method, the system captures the current state of the database, satisfying the requirement to establish a rollback point. When an exception arises, `Database.rollback(sp)` can be called to undo all changes made after the savepoint was defined, ensuring data integrity within the Apex trigger execution context without impacting the entire transaction.

Why this answer

Database.setSavepoint() creates a savepoint, and Database.rollback() rolls back changes to that savepoint.

43
MCQmedium

A developer is writing an Apex trigger on the Case object that updates the Case's Status field based on the Priority. The trigger must handle bulk updates and avoid recursion. Which approach should the developer take to prevent the trigger from firing again when the Case records are updated by the trigger itself?

A.Use Trigger.isExecuting to determine if the trigger is currently executing.
B.Use a static Boolean variable in the trigger handler class to check if the trigger has already run.
C.Use a static Set<Id> to track which records have been processed and skip them in subsequent executions.
D.Use a static Integer to count the number of times the trigger has fired and stop after the first execution.
AnswerB

A static Boolean variable in a handler class persists for the duration of the transaction and can be used to prevent recursive trigger execution. The trigger checks the variable before performing updates and sets it to true after the first run. This is a common and effective pattern to avoid recursion in bulk updates.

Why this answer

A static Boolean variable in a handler class is the standard way to prevent recursive trigger execution. It persists throughout the transaction and can be checked at the start of the trigger to ensure the logic runs only once, even if the trigger is fired again by its own updates.

Exam trap

The trap here is thinking that Trigger.isExecuting can prevent recursion, when it only indicates that a trigger is running, not whether it has already run in the current transaction.

44
MCQmedium

A developer needs to convert a String variable containing a numeric value into an Integer in Apex. Which method should be used?

A.String.toInteger()
B.Convert.toInteger()
C.Integer.valueOf()
D.Integer.parse()
AnswerC

Integer.valueOf() converts a String containing a numeric value into an Integer primitive in Apex, throwing a TypeException if the string is not a valid number. This directly satisfies the requirement to convert a numeric String into an Integer.

Why this answer

Integer.valueOf() converts a String representation of a number into an Integer primitive.

45
MCQeasy

Which method is used to get the number of elements in an Apex List?

A.getNumElements()
B.size()
C.length()
D.count()
AnswerB

Apex List exposes size(), returning the number of elements as an Integer. Unlike arrays in some languages, Apex collections provide no length property, so size() is the method satisfying the stem's requirement for counting elements.

Why this answer

The size() method returns the number of elements in a List, Set, or Map in Apex.

46
Multi-Selecteasy

Which TWO primitive data types are natively supported in Apex? Choose 2 options.

Select 2 answers
A.Char
B.Structure
C.Array
D.Integer
E.Boolean
AnswersD, E

Apex natively supports the Integer data type, which satisfies the requirement to identify a primitive data type within the language. This 32-bit signed value is a fundamental building block used to store whole numbers without decimal points, distinguishing it from complex objects or collections. By providing direct support for this primitive, the platform ensures developers can perform arithmetic operations and manage numeric state efficiently within their code, adhering to the strict typing constraints defined by the Apex runtime environment.

Why this answer

Option D (Integer) is correct because Apex natively supports Integer as a 32-bit signed whole-number primitive type, declared directly as 'Integer i = 5;'. Option E (Boolean) is correct because Apex natively supports Boolean as a primitive type holding only true or false, declared as 'Boolean b = true;'. The unmarked options do not belong: Apex has no 'Char' primitive (single characters are handled with the String type), 'Structure' is not an Apex data type (it is a C/C++-style construct), and 'Array' is not a primitive in Apex—ordered collections are created as Lists (e.g., 'List<Integer>'), which are objects rather than primitives.

47
Multi-Selectmedium

Which TWO statements about SOSL (Salesforce Object Search Language) are true? Choose 2 options.

Select 2 answers
A.SOSL can only query a single object per statement.
B.SOSL can query text across multiple standard and custom objects in a single query.
C.SOSL search results return a list of lists of sObjects.
D.SOSL queries support complex arithmetic calculations and grouping clauses.
E.SOSL queries are executed using the SELECT keyword.
AnswersB, C

Salesforce Object Search Language (SOSL) natively enables text-based searches across multiple standard and custom objects simultaneously via a single programmatic request, satisfying the stem's requirement to query multiple objects concurrently. Unlike SOQL (Salesforce Object Query Language), which is inherently relational and restricted to querying a single sObject and its direct children per execution (unless joined via parent-to-child relationships), SOSL is specifically engineered for full-text indexing retrieval. By leveraging an underlying inverted index, it efficiently tokenises search terms and scans multiple disparate object definitions in one operation.

Why this answer

SOSL searches across multiple objects and returns lists of sObjects grouped by object type.

48
MCQmedium

A developer needs to apply a custom discount to a list of Opportunity records and then persist the changes to Salesforce. The logic must be reusable both from an Apex trigger and from an Apex controller invoked by a Lightning web component. Which approach best satisfies the requirement while following Apex best practices?

A.Write the discount logic in a Visualforce controller and have the trigger call the controller's action method.
B.Place the discount logic directly inside the trigger body so it runs for every DML event.
C.Create a public Apex class with a static method that accepts a List<Opportunity>, applies the discount, and returns the modified list; call it from both the trigger and the controller.
D.Implement the discount as a formula field on Opportunity and let Salesforce recalculate it on every save.
AnswerC

A public class exposing a static method that takes and returns a List<Opportunity> is callable from a trigger, an Apex controller, a batch class, or a queueable. This keeps the discount rule in one place, avoids duplication, and makes the logic unit-testable without firing DML, which aligns with the separation-of-concerns guidance for Apex.

Why this answer

Extracting the discount rule into a public Apex class with a static method that receives and returns a List<Opportunity> gives one authoritative implementation. Triggers, Apex controllers, batch jobs, and queueable classes can all call the same method, which reduces duplication and keeps DML-trigger logic thin. This separation also makes the rule straightforward to unit test in isolation.

Exam trap

The trap here is assuming that logic placed in a trigger is automatically reusable by other Apex entry points, when triggers cannot be invoked directly from a controller.

49
Multi-Selecteasy

Which TWO collection interfaces or classes are provided in Apex? Choose 2 options.

Select 2 answers
A.Vector
B.Dictionary
C.Hashtable
D.Map
E.List
AnswersD, E

Apex provides the `Map` class as a core collection interface, fulfilling the requirement to identify native collection types alongside lists and sets. A map stores data as key-value pairs, allowing developers to efficiently retrieve, update, or remove unique elements based on a distinct key rather than an integer index. This collection type is fundamental for handling relational Salesforce data, especially when caching query results or deduplicating records by a specific field value such as an ID or external identifier.

Why this answer

List and Map are core collection types in Apex.

50
MCQeasy

Which collection type in Apex stores elements as key-value pairs where each key maps to a single value?

A.Set
B.Queue
C.Map
D.List
AnswerC

A Map in Apex directly satisfies the requirement to store elements as unique key-value pairs, where every distinct key maps precisely to a single value. This collection type provides rapid data retrieval by hashing keys, allowing developers to efficiently look up, update, or remove associated values without iterating through the entire collection. Its underlying architecture enforces uniqueness upon the keys, making it the definitive choice for scenarios that demand fast, relational data access based on specific identifiers.

Why this answer

A Map stores key-value pairs where each unique key maps to a single value.

51
MCQhard

An Apex trigger processes a list of Case records. The developer wants to group the cases by their AccountId. Which data structure is best suited for this grouping?

A.List<Map<Id, Case>>
B.Set<Map<Id, Case>>
C.Map<Id, Case>
D.Map<Id, List<Case>>
AnswerD

Grouping a list of Case records by their AccountId requires mapping each unique parent identifier to multiple child records, perfectly satisfying the requirement to handle potential one-to-many relationships where multiple cases share the same account. Using a `Map<Id, List<Case>>` allows the developer to use the AccountId as the key, ensuring rapid O(1) lookups, while storing a `List<Case>` as the value to dynamically collect all associated records without data loss or overwriting during iteration.

Why this answer

A Map where the key is the AccountId (Id) and the value is a List of Cases (List<Case>) allows efficient grouping of child records by parent ID.

52
MCQeasy

Which component of the MVC design pattern in Salesforce Lightning Web Components (LWC) represents the data model and business logic layer?

A.Apex classes and database objects
B.HTML template files
C.CSS style sheets
D.JavaScript controller files
AnswerA

Apex classes running on the server alongside Salesforce database objects directly satisfy the requirement to represent the data model and business logic layer within the MVC architecture. While client-side JavaScript controllers manage the presentation logic and user interface interactions, the combination of Apex and underlying database objects handles persistent data storage, SOQL queries, transactions, and complex server-side execution, fulfilling the precise functional boundaries of the model and logic tier.

Why this answer

In Salesforce, the Model layer corresponds to the database and Apex controllers/SOQL queries handling data.

53
MCQhard

A developer writes an Apex method that executes a SOQL query inside a for-loop over a list of 200 Account records. Which governor limit is most likely to be immediately breached?

A.Total number of SOQL queries issued
B.Total heap size allocation
C.Maximum CPU time on Salesforce servers
D.Total number of records retrieved by SOQL queries
AnswerA

Each loop iteration issues a separate SOQL call, so 200 Accounts consume 200 queries against the synchronous limit of 100. The constraint breached is the total SOQL query count, not rows returned. Bulkifying with a single WHERE Id IN :accountIds query avoids this.

Why this answer

The synchronous limit for SOQL queries is 100 per transaction. Querying inside a loop over 200 records will exceed this limit.

54
MCQhard

An application has complex business logic where an Apex class called from a trigger needs to know whether it was invoked from an insert or update trigger context. How can the developer determine this?

A.Query the Audit Trail object for the active transaction ID.
B.Check Trigger.isInsert and Trigger.isUpdate boolean variables.
C.Check if Trigger.old is null; if null, it is always an update.
D.Inspect the exception stack trace using System.debug().
AnswerB

`Trigger.isInsert` and `Trigger.isUpdate` are context variables provided by the Salesforce execution context, allowing an Apex class called from a trigger to precisely differentiate between operation types. Because the stem requires determining whether the invocation stemmed from an insert or update context, evaluating these boolean properties directly satisfies the requirement without needing custom parameter passing or workarounds.

Why this answer

Trigger.isInsert and Trigger.isUpdate context variables indicate whether the current trigger execution was caused by an insert or update operation.

55
MCQhard

A developer writes an Apex method with the 'inherited sharing' keyword. What is the behavior of this class when invoked from a class declared with 'with sharing'?

A.It throws a compilation error because sharing modes conflict.
B.It executes in system mode without enforcing sharing rules.
C.It enforces sharing rules because the calling class has 'with sharing'.
D.It prompts the user to select a sharing mode at runtime.
AnswerC

Classes declared with `inherited sharing` adopt the sharing context of the class that invokes them. When called from a class defined with `with sharing`, the method executes in an enforced sharing context, thereby satisfying the calling class's restriction. This keyword ensures that the code maintains the security posture of its parent context if no explicit sharing declaration is provided on the class itself.

Why this answer

Inherited sharing classes execute with sharing when invoked from a with sharing context, inheriting the caller's sharing rules.

56
MCQmedium

A developer writes a SOQL query to fetch Account records and wants to bind a list of strings called 'targetNames' as filter criteria. Which syntax is correct?

A.SELECT Id FROM Account WHERE Name IN targetNames
B.SELECT Id FROM Account WHERE Name IN {targetNames}
C.SELECT Id FROM Account WHERE Name IN STRING.valueOf(targetNames)
D.SELECT Id FROM Account WHERE Name IN :targetNames
AnswerD

Binding a collection variable directly within a SOQL query using the colon syntax successfully satisfies the requirement to filter Account records against a list of strings called 'targetNames'. Apex run-time evaluates the `:` prefix as a bind variable, automatically serialising the entire collection into a comma-separated list enclosed in parentheses. This mechanism prevents SOQL injection vulnerabilities while efficiently handling multiple string criteria within the `IN` operator, avoiding the need for manual string concatenation or iterative query construction.

Why this answer

Using IN :targetNames allows binding a collection variable directly into a SOQL WHERE clause.

57
Multi-Selectmedium

Which TWO types of triggers can be defined in Apex? Choose 2 options.

Select 2 answers
A.after trigger
B.instead of trigger
C.commit trigger
D.before trigger
E.validation trigger
AnswersA, D

An `after` trigger executes subsequent to database operations committing records, which directly satisfies one of the two core trigger timing types requested in the stem. During this execution phase, record IDs are fully generated and system-generated fields are populated, allowing developers to access read-only record contexts and reliably perform related-record manipulations or cross-object operations on parent and child objects within the same transactional boundary.

Why this answer

In Apex, the two supported trigger types are before triggers (option D) and after triggers (option A). A before trigger fires before records are saved to the database and is used to validate or modify field values on the incoming records, while an after trigger fires after records are committed and is used to access system-set fields like Id or to perform related-record DML. Apex does not support instead of triggers (option B), which exist in T-SQL for views; commit triggers (option C) are not an Apex construct; and validation triggers (option E) are not a trigger type—validation is handled by before triggers or validation rules.

58
Multi-Selecthard

Which THREE statements are accurate regarding Apex transaction control and database savepoints? Choose 3 answers.

Select 3 answers
A.Database.setSavepoint() returns a Savepoint object reference.
B.Establishing a savepoint resets the SOQL query governor limit counter.
C.Rolling back to a savepoint clears all governor limit exceptions already thrown.
D.You can set multiple savepoints within a single transaction.
E.Savepoints allow developers to roll back part of a transaction after encountering errors.
AnswersA, D, E

`Database.setSavepoint()` captures the current state of an Apex transaction and explicitly returns a `Savepoint` object reference. This returned reference is a mandatory parameter for subsequent rollback operations using `Database.rollback()`, satisfying the core requirement of transaction control where developers must manage and revert partial DML failures within a single execution context. Storing this object reference allows code to safely target and restore the exact database state established at the moment the savepoint was initially invoked.

Why this answer

Savepoints allow partial rollbacks within a single transaction using Database.setSavepoint() and Database.rollback().

59
MCQmedium

A developer writes a SOQL query using the FORMAT() keyword. What is the purpose of this keyword?

A.To ensure SOQL query syntax is validated before execution
B.To return number, date, and currency fields formatted according to the user's locale
C.To format query results into JSON format
D.To convert string fields into uppercase
AnswerB

The `FORMAT()` keyword in SOQL applies locale-specific formatting directly to number, date, time, and currency fields within the query result set. This satisfies the requirement stated in the question stem by leveraging the running user's personal locale settings—such as specific date structures and currency symbols—without requiring developers to manually parse and transform raw database values in Apex code.

Why this answer

FORMAT() formats currency, date, time, and numerical fields according to the current user's locale settings.

60
MCQhard

An Apex trigger executes a query inside a for-loop to fetch related child records for every parent Account in Trigger.new. The developer notices that when a data load of 200 accounts occurs, the governor limit for total SOQL queries issued is exceeded. How should the developer refactor the code?

A.Annotate the trigger with @ReadOnly to increase the query limit.
B.Wrap the query in a try-catch block and catch the QueryException.
C.Use the Database.executeBatch method to process each account in a separate transaction.
D.Collect the Account IDs in a Set and execute a single SOQL query outside the loop using the IN operator.
AnswerD

Moving the query outside the loop replaces 200 per-parent SOQL calls with one bulk query, satisfying the total SOQL governor limit. Gathering IDs into a Set and filtering with IN preserves correctness while issuing a single query.

Why this answer

To avoid hitting the governor limit of 100 SOQL queries per transaction, queries must be moved outside of loops and bulkified using collections.

61
Multi-Selecteasy

Which THREE data types are primitive data types supported in Apex? (Choose three.)

Select 3 answers
A.Boolean
B.WorkflowRule
C.Integer
D.LightningComponent
E.String
AnswersA, C, E

Boolean is a fundamental primitive data type natively supported in Apex, directly satisfying the stem's constraint to select a primitive data type. In Apex, primitive types are passed by value and represent single, indivisible values rather than complex database objects or sObjects. The Boolean type specifically holds a truth value of true, false, or null, making it one of the foundational building blocks alongside other primitives like Integer, Double, and String for basic variable declarations and logical evaluations within developer code.

Why this answer

Apex supports standard primitive types including Boolean, Integer, and String.

62
MCQmedium

A developer is writing a test class for an Apex trigger and needs to insert test Account records. Best practices recommend bypassing hardcoded IDs. Which annotation should be placed on the test setup method to create common test data efficiently?

A.@IsTest(SeeAllData=true)
B.@TestVisible
C.@RemoteAction
D.@TestSetup
AnswerD

@TestSetup runs once before all test methods in the class, creating shared Account records that every method reuses. This satisfies the stem's efficiency and hardcoded-ID-avoidance constraints, since data is inserted via normal DML rather than fixed record IDs.

Why this answer

The @TestSetup annotation allows developers to create test records once and make them available for all test methods in the class.

63
MCQmedium

A developer wants to ensure that a custom Apex controller method can be invoked securely from a Lightning Web Component. Which annotation must be applied to the method?

A.@AuraEnabled
B.@InvocableMethod
C.@RemoteAction
D.@WebService
AnswerA

Applying the `@AuraEnabled` annotation to a custom Apex method explicitly exposes it to the Lightning Component framework, satisfying the security and accessibility requirement needed for a Lightning Web Component to invoke server-side logic. Without this annotation, the controller method remains hidden from client-side JavaScript execution in the Salesforce platform, preventing unauthorised or accidental remote calls. Additionally, setting `@AuraEnabled(cacheable=true)` allows read-only methods to cache data on the client side, optimising performance when fetching records from the database.

Why this answer

@AuraEnabled enables methods to be called from Lightning components and can also cache data.

64
MCQhard

A developer needs to implement a custom logging framework. Which Apex data type should be used to represent a variable that can store any primitive value, sObject, or collection dynamically?

A.Any
B.Variant
C.Object
D.Dynamic
AnswerC

The `Object` data type in Apex is the universal base type capable of implicitly casting to and from any primitive data type, sObject, or collection. This satisfies the strict architectural constraint in the stem requiring a single dynamic variable type to store heterogeneous payloads without prior type casting. Unlike strongly typed declarations or generic wrappers, `Object` variables evaluate their runtime type dynamically, allowing developers to write flexible logging routines that accept arbitrary data structures at execution time.

Why this answer

The Object data type is the base data type in Apex and can hold any value, including primitives, sObjects, and collections.

65
MCQeasy

A developer needs to store a collection of unique customer email addresses in Apex and check for existence efficiently. Which collection type should the developer use?

A.Queueable
B.List
C.Map
D.Set
AnswerD

Set stores only unique elements and provides constant-time contains() lookups via hashing, so duplicate emails collapse automatically and existence checks avoid scanning. This satisfies the uniqueness and efficient existence-checking constraints, which List and Map do not address as directly.

Why this answer

A Set is a collection of unique elements and provides efficient lookup using methods like contains(), making it ideal for checking existence.

66
MCQmedium

An Apex trigger needs to check whether the current user has read access to the 'AnnualRevenue' field on the Account object before performing a calculation. Which method should the developer use?

A.Schema.sObjectType.Account.fields.AnnualRevenue.getDescribe().isAccessible()
B.User.hasReadAccess('Account', 'AnnualRevenue')
C.Account.AnnualRevenue.getDescribe().isAccessible()
D.System.checkFieldAccess(Account.class, 'AnnualRevenue', 'Read')
AnswerA

Traversing the sObject schema hierarchy via `Schema.sObjectType.Account.fields.AnnualRevenue.getDescribe()` accesses the field-level metadata natively within Apex. Calling the `.isAccessible()` method on this description object evaluates the running user's runtime field-level security permissions, satisfying the stem's requirement to check read access on the 'AnnualRevenue' field prior to executing the calculation.

Why this answer

Schema.sObjectType.Account.fields.AnnualRevenue.getDescribe().isAccessible() checks field-level security for the current user in Apex.

67
Multi-Selecthard

Which THREE design patterns or tools help ensure secure coding practices regarding CRUD and FLS in Apex? Choose 3 options.

Select 3 answers
A.Using Security.stripInaccessible() before upserting data.
B.Adding WITH SECURITY_ENFORCED to SOQL queries.
C.Performing explicit Schema describe checks (e.g., isAccessible()).
D.Declaring every class with 'without sharing'.
E.Relying solely on Lightning Web Component HTML rendering tags.
AnswersA, B, C

`Security.stripInaccessible()` directly satisfies the requirement to enforce object- and field-level security (FLS) dynamically in Apex by automatically stripping inaccessible fields and sObjects from query and subquery results, or before performing DML operations like upserts. By inspecting the running user's permissions against the schema at runtime, this built-in method prevents unauthorised data exposure and insecure mutations without throwing exceptions, making it an essential tool for secure coding practices regarding CRUD and FLS compliance.

Why this answer

Option A is correct because Security.stripInaccessible() programmatically removes fields the running user cannot create or update (based on CRUD/FLS) from sObjects before a DML operation such as upsert, preventing unauthorized field writes. Option B is correct because adding WITH SECURITY_ENFORCED to a SOQL query enforces field- and object-level security at query time, throwing an exception if the user lacks access to any referenced field or object. Option C is correct because explicit Schema describe checks like Schema.sObjectType.Account.fields.Name.isAccessible() (and isCreateable()/isUpdateable()) let developers enforce FLS/CRUD manually before reading or writing data.

Option D is incorrect because declaring classes 'without sharing' bypasses record-level sharing and does nothing to enforce CRUD or FLS, weakening security. Option E is incorrect because LWC HTML rendering tags only affect client-side display and cannot enforce server-side CRUD/FLS in Apex.

68
MCQeasy

Which type of Apex trigger context variable returns a list of new versions of the sObject records?

A.Trigger.new
B.Trigger.newMap
C.Trigger.old
D.Trigger.caller
AnswerA

`Trigger.new` directly satisfies the requirement specified in the stem by returning a collection of sObject records that represent the updated or newly created versions of the records in question. This context variable provides in-memory access to the incoming records during before and after insert, update, and undelete trigger executions, allowing developers to inspect and manipulate field values prior to database operations or subsequent execution logic.

Why this answer

Trigger.new contains all the new versions of the sObject records for insert and update triggers.

69
MCQhard

An Apex trigger processes a large volume of Opportunity updates. The developer uses Database.update(opps, false) to allow partial success. How should the developer inspect the results to handle any failures?

A.Inspect the Trigger.errors context variable.
B.Wrap the Database.update call in a try-catch block and inspect the DMLException methods.
C.Iterate over the returned List<Database.SaveResult> and check the isSuccess() method.
D.Query the AsyncApexJob object to check for error logs.
AnswerC

Using `Database.update(opps, false)` returns a collection of `Database.SaveResult` objects that correspond directly to the input records. To handle failures properly during bulk processing, the developer must iterate through this returned list and invoke the `isSuccess()` method on each instance. This satisfies the requirement to inspect partial success results without causing unhandled exceptions, allowing the code to isolate and log specific error messages using `getErrors()` for any failed records.

Why this answer

Database methods returning partial success provide a list of Database.SaveResult objects that contain error details.

70
MCQhard

A developer writes an Apex method that executes a SOQL query using user-supplied search parameters. How can the developer protect against SOQL injection vulnerabilities?

A.Execute the query using Database.queryWithBinds() with a restricted access modifier.
B.Use bind variables in the SOQL query instead of string concatenation.
C.Use String.escapeSingleQuotes() on all user inputs before concatenating into the query string.
D.Enclose all dynamic parameters in single quotes within the dynamic SOQL query string.
AnswerB

Using bind variables satisfies the constraint of executing a SOQL query using user-supplied search parameters securely. When developers integrate dynamic user input via string concatenation, malicious actors can manipulate the query logic. By substituting string concatenation with bind variables (using the colon syntax, such as `:userInput`), the Salesforce platform treats the input strictly as a literal value rather than executable query syntax. This completely neutralises SOQL injection attempts, ensuring the query structure remains unaltered regardless of the input's content.

Why this answer

Using bind variables in SOQL queries automatically sanitizes the input and prevents SOQL injection, unlike string concatenation.

71
MCQmedium

A developer needs to execute a dynamic SOQL query where the object name and fields are determined at runtime. Which method should be used?

A.Record.query()
B.System.query()
C.SOQL.query()
D.Database.query()
AnswerD

`Database.query()` accepts a string variable as its sole argument, allowing developers to construct SOQL statements dynamically by concatenating object names and field identifiers at runtime. This capability directly satisfies the requirement to handle variable schema elements that are unknown during compilation. Unlike static SOQL, which requires hard-coded object and field references, this method processes the query string during execution, providing the necessary flexibility to adapt to changing runtime parameters while maintaining full integration with the Salesforce database engine.

Why this answer

Database.query() allows execution of dynamically constructed SOQL query strings.

72
MCQeasy

Which primitive data type in Apex can represent a specific point in time, including both date and time values?

A.Date
B.Time
C.Datetime
D.Timestamp
AnswerC

The Datetime data type serves as the standard Apex primitive for capturing both calendar dates and clock times within a single variable. By storing values as Coordinated Universal Time (UTC) milliseconds, it satisfies the stem’s requirement for a specific point in time. Unlike the Date type, which lacks temporal precision, Datetime provides the necessary granularity to track events or timestamps accurately, ensuring developers can perform precise arithmetic and comparisons across different time zones when integrating with systems like Microsoft Entra ID.

Why this answer

The Datetime data type represents both a date and a time in Apex.

73
MCQhard

A developer needs to iterate over a map of Account IDs to Account sObjects and perform processing on each value. Which loop construct is valid Apex?

A.for(KeyValue kv : myMap.entrySet()) { ... }
B.for(Account acc : myMap) { ... }
C.for(Account acc : myMap.values()) { ... }
D.for(Id id : myMap.iterator()) { ... }
AnswerC

Apex maps expose a values() method returning a collection of the map's values, which is iterable with the enhanced for-loop. Since the map is keyed by ID with Account sObjects as values, iterating values() yields each Account directly, matching the required processing.

Why this answer

Iterating over map values is done using map.values() in a for-loop: for(Account acc : myMap.values()).

74
MCQeasy

A developer is writing an Apex method and needs to store a collection of unique email addresses while maintaining fast lookup times. Which collection should the developer choose?

A.List<String>
B.Queue<String>
C.Map<String, Integer>
D.Set<String>
AnswerD

A `Set<String>` automatically enforces uniqueness by preventing duplicate entries, which directly satisfies the requirement for storing unique email addresses. Internally, Apex sets utilise a hash table implementation to ensure that lookups, additions, and removals occur in constant time, $O(1)$, on average. This high-performance mechanism provides the fast lookup times necessary for efficient data retrieval within an Apex method, making it the optimal choice for managing collections where uniqueness and rapid access are the primary technical constraints.

Why this answer

Sets in Apex store unique elements and provide efficient membership testing methods like contains().

75
MCQmedium

A developer needs to query all Contact records, including those that have been deleted from the database via the Recycle Bin. Which SOQL clause must be added?

A.INCLUDING DELETED
B.FOR VIEW
C.FOR REFERENCE
D.ALL ROWS
AnswerD

Including the ALL ROWS clause in a SOQL query explicitly instructs the database engine to bypass the default filter that excludes soft-deleted records. By satisfying the requirement to retrieve data currently residing in the Recycle Bin, this keyword extends the query scope beyond active records. This mechanism is essential for auditing or recovering information that has not yet been permanently purged from the system, ensuring the developer can access the complete dataset regardless of its current lifecycle state within the platform.

Why this answer

ALL ROWS must be appended to a SOQL query to include records in the Recycle Bin (deleted records) and archived tasks/events.

Page 1 of 2 · 76 questions totalNext →

Ready to test yourself?

Try a timed practice session using only Developer Fundamentals questions.