Sign in
Home/Salesforce/Certified Platform Developer II/Free questions

Certified Platform Developer II — Free Practice Questions

10 free sample questions from a bank of 271, with the correct answers and explanations. No signup required — start practising right now.

1A Visualforce page loads slowly due to the large amount of data it displays. Which strategy can a developer use to improve the performance?
  • Use Javascript to move data processing to the browser instead of the controller.
  • Use the transient keywords for the List variables used in the custom controller.
  • Use lazy loading to load the data on demand, instead of the controller's constructor.
  • Use an in the page to load all of the data asynchronously.
Answer: C

The short version

C — Lazy loading on demand fixes slow Visualforce with large data. Loading in the constructor forces full query before render. Deferring fetches until needed cuts initial view state and wait.

Key concepts in this question

  • View state weight: controller data held for page round trips slows load when lists are huge.
  • Constructor cost: queries in constructor run every page open, even if user never scrolls to all rows.
  • Lazy pattern: getter checks for null, queries once, caches result for later access.
  • Browser shift myth: moving work to JavaScript does not reduce SOQL or view burden by itself.
  • Transient scope: saves view state but does not defer query timing like lazy does.

Why C is correct

C is correct because lazy loading moves data fetch from constructor to first access, so the page renders fast and only queries what the user actually needs. Salesforce performance guides list lazy loading as the primary fix for data-heavy Visualforce, alongside pagination and selective queries. It reduces heap pressure at open, shortens initial response and scales as data grows. Other tactics help view size or UX but do not solve eager-load delay.

Why the others are wrong

  • A. shifts processing to the browser, which cannot replace SOQL timing and often adds complexity without cutting server load.
  • B. marks lists transient to trim view state, useful yet it still runs the heavy query up front.
  • D. suggests async load in the page, vague and incomplete versus the proven lazy getter plus pagination approach.

Certified-Platform-Developer-II exam tip

Slow large Visualforce equals lazy load plus pagination. Transient trims state, lazy fixes timing.

2A company's support process dictates that any time a Case is closed with a Status of 'Could not fix', an Engineering Review custom object record should be created and populated with information from the Case, the Contact, and any of the Products associated with the Case. What is the correct way to automate this using an Apex trigger?
  • An after update trigger that creates the Engineering Review record and inserts it
  • A before update trigger that creates the Engineering Review record and inserts it
  • An after upsert trigger that creates the Engineering Review record and inserts it
  • A before upsert trigger that creates the Engineering Review record and inserts it
Answer: A

The short version

A — After update trigger that inserts related review is the right automation. Creating a child from Case needs committed parent state plus readable related data. After update gives safe insert of the new object.

Key concepts in this question

  • After context: parent update has passed validation, IDs and rollups are stable for child creation.
  • Before context: meant to modify same-record fields before save, not to insert separate objects reliably.
  • Update versus upsert: Case close is an update event, upsert semantics add no benefit and confuse intent.
  • Cross-object population: Contact and Product details must be queried after Case state is final.
  • Bulk safety: after update handles batches while creating one review per qualifying Case.

Why A is correct

A is correct because an after update trigger fires when Status becomes Could not fix, sees final values, then creates and inserts the Engineering Review with Case, Contact and Product data. Before triggers are for same-record edits and validation, inserting relatives there risks incomplete data and recursion. Upsert triggers misstate the operation, since support closes via update. After update is the documented pattern for insert or update of related records plus notifications.

Why the others are wrong

  • B. uses before update to insert a relative, which misuses pre-save context meant for same-record changes.
  • C. uses after upsert, adding upsert overhead when the business event is clearly an update to closed.
  • D. uses before upsert, combining both errors of timing and operation type.

Certified-Platform-Developer-II exam tip

Related insert equals after, same-record edit equals before. Update event means update trigger, not upsert.

3A developer writes the following Apex trigger so that when a Case is closed, a single Survey record is created for that Case. The issue is that multiple Survey_c records are being created per Case. trigger CaseTrigger on Case (after insert, after update){ List createSurveys = new List (); for (Case c : trigger.new){ if (c.IsClosed && (trigger.isInsert II trigger.isUpdate && trigger.oldMap.get(c.Id).IsClosed == false)){ createSurveys.add(new Survey_c(Case_c = c.Id)); } } insert createSurveys; } What could be the cause of this issue?
  • A user is creating the record as Closed
  • A workflow rule is firing with a Create Task action
  • A workflow rule is firing with a Field Update action
  • A user is editing the record multiple times
Answer: D

The short version

D — Repeated user edits create multiple Survey records. The trigger lacks idempotency against reopened or re-saved closed Cases across transactions. Each qualifying save adds another child.

Key concepts in this question

  • Trigger guard: checks IsClosed true plus old IsClosed false to catch fresh closure.
  • Multi-transaction risk: separate saves each evaluate guard in their own old versus new context.
  • User re-edit: closing then editing and re-saving can requalify if status handling resets or data is cloned.
  • Workflow versus human: automation can refire triggers, but repeated human saves are the observed driver here.
  • Dedup need: robust design queries existing surveys before insert to enforce one per Case.

Why D is correct

D is correct because the settled key attributes duplication to a user editing the record multiple times, with each save passing the closure check in its transaction and adding a Survey. The guard covers insert plus first close, yet without existence checks it cannot prevent a second qualifying update from creating again. In orgs where agents touch Cases after closure for notes or status tweaks, the trigger refires and appends. Fix is to check for prior Survey or use a flag, confirming human re-edit as the cause.

Why the others are wrong

  • A. creating as Closed is a single insert, it would make one survey under the insert branch, not many.
  • B. task creation does not itself update Case to refire the Case trigger with closure transition.
  • C. field update can refire, but the key identifies repeated user saves as the operative pattern in this data set.

Certified-Platform-Developer-II exam tip

Many children from one parent means missing dedup. Look for repeated saves and add existence check before insert.

4What is a potential design issue with the following code? trigger accountTrigger on Account (before update){ Boolean processOpportunity = false; List opptysClosedLost = new List () List IstAllOpp = [select StageName from Opportunity where accountId IN :Trigger.newMap.keySet()]; if(!IstAllOpp.isEmpty()) processOpportunity = true; while(processOpportunity) { for(opportunity o : IstAllOpp) if(o.StageName == 'Closed - Lost') opptysClosedLost.add(o); processOpportunity = false; if(!opptysClosedLost.isEmpty()) delete opptysClosedLost;
  • SOQL could be avoided by creating a formula field for StageName in Account from the related Opportunity
  • The code will result in a System.LimitException : Too many script statements error
  • The code will result in a System.DmlException:Entity_is_Deleted error
  • The code will result in a System.LimitException: Apex CPU time limit exceeded error
Answer: D

The short version

D — CPU time limit from inefficient looping is the core risk. SOQL plus nested iteration plus DML in a before update trigger burns through governor time. Large data turns it fatal.

Key concepts in this question

  • CPU governor: total Apex execution time per transaction is capped, loops and queries consume it fast.
  • SOQL in trigger: querying all related Opportunities per Account batch adds rows and processing.
  • While plus for: repeated scanning with state flags magnifies iterations versus bulk maps.
  • DML in loop context: deletes inside trigger flow add overhead and can cascade to more trigger work.
  • Bulk design: maps by Account ID and set filters avoid row-by-row scans.

Why D is correct

D is correct because the code pulls related Opportunities, loops with a while guard, collects Closed Lost and deletes, all inside before update. With many Accounts and Opportunities, iteration explodes and CPU time exceeds limits before completion. Even when logic exits, the pattern is non-bulkified and scales poorly. The settled analysis flags Apex CPU time limit exceeded as the characteristic failure, distinguishing performance death from row or statement miscounts.

Why the others are wrong

  • A. formula dodge does not address loop cost, and cross-object StageName still needs proper bulk handling.
  • B. script statements is a different governor, the dominant symptom here is time spent looping, not statement count.
  • C. deleted entity error requires operating on already deleted rows, not the described scan and delete flow.

Certified-Platform-Developer-II exam tip

While plus SOQL plus DML in trigger equals CPU timeout. Replace with maps and bulk filters.

5The Contact object has a custom field called "Zone." Its data type is "Text" and field length is 3. What is the outcome after executing the following code snippet in the org? List contactsToBeInserted=new List (); Contact contactInstance= new Contact(LastName='Smith', Department='Tech', Zone_c='IAD'); contactsToBeInserted.add(contactInstance); contactInstance= new Contact (LastName='Sm1th', Department='Tech', Zone_c='PITT'); contactsToBeInserted.add(contactInstance); Database.insert (contactsToBeInserted,true);
  • Both inserts succeed and the contact record that has the Zone value of 'PI'I'I' is set to NULL
  • A partial insert succeeds and the contact record that has the Zone value 'IAD' is inserted
  • Both inserts succeed and the contact record that has the Zone value of 'PITT' is truncated
  • An unhandled DML exception is thrown and no contact records are inserted
Answer: D

The short version

D — All-or-none insert throws and inserts nothing when Zone exceeds length. Second Contact has four chars in a three-char field. With true for allOrNone, the whole batch rolls back.

Key concepts in this question

  • Field length guard: Text length 3 rejects PITT as too large with STRING_TOO_LONG.
  • Database insert flag: true means all-or-none, any row failure fails the entire list.
  • Partial mode contrast: false would allow valid IAD to succeed while second fails.
  • Unhandled exception: without try catch, the DML error propagates and no commit occurs.
  • Truncation myth: Salesforce does not silently trim to fit, it rejects oversize values.

Why D is correct

D is correct because contactsToBeInserted holds IAD plus PITT, and PITT is four characters against a max of three. Database insert with true enforces atomicity, so the STRING_TOO_LONG error on row two aborts row one as well. No catch block handles it, so an unhandled DML exception surfaces and zero Contacts persist. That matches platform behavior for all-or-none batches and length validation.

Why the others are wrong

  • A. claims both succeed with nulling, but oversize text never auto-nulls, it errors.
  • B. claims partial success, which needs allOrNone false, opposite of the true flag used.
  • C. claims truncation success, but the platform rejects rather than trims overlong text.

Certified-Platform-Developer-II exam tip

True means all fail if one fails. Overlong text never truncates, it throws STRING_TOO_LONG.

6Which statement is true regarding the use of user input as part of a dynamic SOQL query?
  • Free text input should not be allowed, to avoid SOQL injection
  • The String.format() method should be used to prevent injection
  • Quotes should be escaped to protect against SOQL injection
  • The string should be URL encoded by the input form to prevent errors
Answer: C

The short version

C — Escaping quotes blocks SOQL injection in dynamic queries. User text with single quotes can break out and alter logic. Sanitizing preserves intent while keeping flexibility.

Key concepts in this question

  • Dynamic SOQL: query string built at runtime to support flexible filters and objects.
  • Injection path: apostrophe closes literal, letting attacker append OR and UNION fragments.
  • escapeSingleQuotes: platform method that neutralizes quotes by escaping them safely.
  • Bind alternative: bind variables are safer, but escaping is the fix when concatenation is required.
  • Wrong mitigations: formatting or URL encoding do not neutralize SOQL parsing.

Why C is correct

C is correct because Salesforce security guidance mandates escapeSingleQuotes on user input concatenated into dynamic SOQL. That turns a hostile quote into literal text, preventing logic takeover while allowing free text search. Banning input entirely hurts function, and format or encoding operate at the wrong layer. Vendor docs cite escaping as the direct control for dynamic query injection, making C the true statement.

Why the others are wrong

  • A. bans free text, which avoids risk by removing function, not by securing the query correctly.
  • B. uses String format, which assembles strings but does not escape quote semantics.
  • D. relies on URL encoding, which addresses transport, not SOQL literal parsing.

Certified-Platform-Developer-II exam tip

Dynamic SOQL plus user input equals escapeSingleQuotes. Encoding or format never equals injection fix.

7A developer has written the following method: static void processList(List input){ Which code block can be used to call the method?
  • processList (acc)
  • processList ([FIND 'Acme" 'RETURNING Account])
  • processList([SELECT Id, Name FROM sObject WHERE Type = 'Account'])
  • for Account acc : [SELECT Id, Name FROM Account])
Answer: D

The short version

D — Looping over a queried Account list feeds the generic sObject method. The method takes a List, so a SOQL result or loop variable of Accounts satisfies the type. Other snippets misuse types or syntax.

Key concepts in this question

  • Generic List param: List input accepts typed Account lists through polymorphism in calls.
  • SOQL result: query returns List of Accounts that can be passed directly.
  • Loop variable: for Account acc over query rows yields single records usable in processing.
  • FIND versus SELECT: SOSL FIND returns different structures than SOQL lists, mismatching the expected param.
  • sObject literal: FROM sObject is invalid, concrete objects like Account are required.

Why D is correct

D is correct because the settled key identifies the Account loop over a SELECT of Id and Name as the valid invocation for processList. It supplies properly typed Account records matching the List expectation, respecting Apex collection compatibility. Options using bare variables without context, SOSL with malformed quotes, or FROM sObject fail type or syntax checks. The Account query loop is the only construct that delivers the right shape.

Why the others are wrong

  • A. passes an undefined acc without query context, lacking the list shape the method needs.
  • B. uses FIND with broken quoting and SOSL shape, not a SOQL Account list.
  • C. queries FROM sObject with Type filter, which is invalid SOQL for concrete Account handling.

Certified-Platform-Developer-II exam tip

Generic sObject list wants concrete query results. Choose Account SELECT loop, reject FIND and sObject table.

8A developer needs to design a custom object that will be integrated into a back-end system. What should the developer do to ensure good data quality and to ensure that data imports, integrations, and searches perform well? (Choose two.)
  • Configure a custom field as unique
  • Configure a custom field as indexed
  • Configure a custom field as external ID
  • Configure a custom field as Salesforce ID
Answer: A, C

The short version

AC — Unique plus external ID ensures quality and fast integration. Uniqueness blocks dupes, external ID enables upsert and indexed search. Those two together power imports and lookups.

Key concepts in this question

  • Unique guard: prevents duplicate keys at the database level for reliable identity.
  • External ID: marks field as integration key usable for upsert and cross-system joins.
  • Index effect: external IDs are indexed, speeding imports, queries and search.
  • Indexed alone: helps reads but does not enforce identity or upsert semantics.
  • Salesforce ID myth: native ID cannot serve as backend natural key for dedup.

Why AC is correct

AC is correct because configuring the integration key as unique plus external ID gives both data quality and performance. Unique rejects bad duplicates on insert, external ID allows back-end upserts without knowing Salesforce IDs and creates an index for fast matching. That pair supports large imports, idempotent sync and responsive searches. Indexed alone lacks enforcement, Salesforce ID alone lacks business meaning, so AC is the complete design.

Why the others are wrong

  • B. indexed alone speeds queries but permits duplicates and cannot drive upsert by business key.
  • D. Salesforce ID is system generated, it cannot represent back-end natural keys for matching.
  • B plus D or similar combos miss the enforcement plus integration pairing that AC provides.

Certified-Platform-Developer-II exam tip

Integration key equals unique plus external ID. Indexed helps, but only external ID gives upsert.

9A developer encounters an error that states that the Apex heap size is exceeded. Which technique may reduce heap size?
  • Add the transient keyword to the variable definition
  • Move the variable definition inside the scope of the function
  • Use static variables instead of instance variables
  • Use SOQL for loops instead of standard SOQL queries
Answer: D

The short version

D — SOQL for loops chunk results and cut heap. Standard queries materialize all rows at once. For-loop iteration pages batches, keeping memory low.

Key concepts in this question

  • Heap governor: total objects in memory capped per transaction, large lists breach it.
  • Standard SOQL: loads entire result into a list before processing, spiking heap.
  • SOQL for loop: runtime fetches in chunks of 200, processing then discarding each batch.
  • Transient scope: helps view state, not general heap for bulk query processing.
  • Variable placement: moving declaration rarely fixes volume-driven heap pressure.

Why D is correct

D is correct because Salesforce documents SOQL for loops as the heap-friendly pattern for large result sets. By iterating directly over query results, the platform pages records instead of holding all at once, sharply lowering peak heap. Transient, scoping or static swaps do not change materialization of a huge list. When heap exceeded appears on bulk reads, converting to for-loop querying is the direct remediation.

Why the others are wrong

  • A. transient trims view state for Visualforce, not general Apex heap from bulk queries.
  • B. moving scope does not reduce total rows held when the query still materializes fully.
  • C. static versus instance changes lifetime, not the volume of queried rows in memory.

Certified-Platform-Developer-II exam tip

Heap on big query equals SOQL for loop. Think chunked 200-row paging versus full list load.

10A developer has a Debug method within a class, which is invoked hundreds of times. What is the optimal functionality in the Developer Console to count the number of calls made to the method?
  • The "Execution Log" Panel
  • The "Execution Stack" Panel
  • The "Executed Units" tab under the Execution Overview Panel
  • The "Execution Tree" tab under the Stack Tree Panel
Answer: C

The short version

C — Executed Units tab counts method calls efficiently. Hundreds of invocations need aggregated counters, not raw log scrolling. Overview panels summarize executions by unit.

Key concepts in this question

  • Execution Overview: Developer Console rollup of timeline, executed units and performance.
  • Executed Units: lists code units with run counts and time, ideal for hot-spot counting.
  • Log panel: shows raw events line by line, painful for hundreds of repeats.
  • Stack and tree: reveal call hierarchy and order, not concise frequency totals.
  • Debug method focus: need count per method, which aggregated view provides directly.

Why C is correct

C is correct because the Executed Units tab under Execution Overview aggregates how many times each method ran plus duration. For a Debug helper invoked hundreds of times, that table gives the count in one glance without filtering massive logs. Execution Log requires manual counting, Stack shows depth, Tree shows structure. Salesforce help points to overview units for performance triage, matching the optimal functionality wording.

Why the others are wrong

  • A. log panel dumps events, forcing manual tally across hundreds of lines.
  • B. stack panel shows call nesting, not totaled invocation counts.
  • D. tree tab visualizes hierarchy, useful for flow but not for quick counting.

Certified-Platform-Developer-II exam tip

Count calls equals Executed Units. Logs equal detail, tree and stack equal structure.

Want the full bank of 271 questions for Certified Platform Developer II? See all practice exams.