Interview Questions Customization Coding Prafulla
Interview Questions Customization Coding Prafulla
Ans: Interface is a collection of unimplemented methods. This will specify the signature of the method,
types of inputs that we pass the method specify what type is given as an output.
Note: Generally the interface methods we give it as global.
Q. What are Wrapper Classes in Salesforce? Give an example where you can use wrapper class!
A wrapper class in Salesforce is a Container Class which contains Objects, Collection of Objects,
variables, Collection of other classes as its member. We can also say that a wrapper class is a custom
object that Programmer defines to achieve the business need and defines the properties inside the
class.
Wrapper Class
b) OR we can use Wrapper class when we want to show the list of data in VF page or in any other classes
of the many objects that are not related to each other.
Q. What is the difference between Trigger.new and Trigger.old and Trigger.newmap and
Trigger.oldmap ?
Trigger.new returns new records and Trigger.old return data before updates were done.
Trigger.newmap returns new records with id's and Trigger.oldmap return data before updates were
done with id's.
In following trigger, we are checking if static variable is true only then trigger runs. Also we are setting
static variable to false when trigger runs for first time. So if trigger will try to run second time in same
request then it will not run.
Static SOQL:
The Static SOQL Statement is written in [](Array Brackets)
These statements are similar to IINQ (Ion Integrated Query)
Example 1:
String search for =’Jones’;
Contact[] contacts=[select testfield__c, FirstName, LastName from Contact Where Last Name=:search
for];
Dynamic SOQL:
It is used to refer to the creation of a SOQL string at run time with Apex code.
Dynamic SOQL enables you to create a more flexible application.
To create a Dynamic SOQL query at run time use Database.Query() method, in one of the following
ways.
Return a single sObjects when the query returns a single record.
sObjects s = Database. Query(String_limit_l);
Return a list of sObjects when the query returns more than a single record.
Example 1:- Queries
String myTestString = ‘TestName’;
List List= Database.Query(SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString);
14) What are the different types of Apex code development tools?
A) In all versions, we can use the following three tools to develop code:
Force.com Developer Console
Force.com IDE
Code editor in the Salesforce UI
17) Can you write simple example code for sObject in Apex?
A) Here is the sample code for sObject,
//Declaring an sObject variable of type Account
Account objAccount = new Account();
//Assignment of values to fields of sObjects
objAccount.Name = ‘ABC Customer’;
objAccount.Description = ‘Test Account’;
System.debug(‘objAccount variable value’+objAccount);
//Declaring an sObject for custom object APEX_Invoice_c
APEX_Customer_c objCustomer = new APEX_Customer_c();
//Assigning value to fields
objCustomer.APEX_Customer_Decscription_c = ‘Test Customer’;
System.debug(‘value objCustomer’+objCustomer);
18) What in Enum in Apex?
A) An enumeration is an abstract data type that stores a value of a finite set of specified identifiers. You
can define an enumeration using the keyword Enum. Enumerations can be used as any other data type
in Salesforce.
19) Can you write sample example code for enumeration in Apex?
A) Here is the sample example code for enum,
Assuming you want to declare the possible name of the compound, then you can do this:
//Declaring enum for Chemical Compounds
Public enum Compounds {HCL, H2SO4, NACL, HG}
Compounds objC = Compounds.HCL;
System.debug(‘objC value: ‘+objC);
Batch Apex:
Q. What is Batch Apex in Salesforce?
Ans: Batch Apex allows you to define a single job that can be broken up into manageable chunks,
whereas every chunk can be processed separately. In the Batch Apex it will fetch all the records on
which you want to perform the field update and divide them into a list of 200 records and on every 200
records operation are performed separately.
This would help us to execute on more than 10,000 records as it won’t perform an operation on all the
records in a single transaction instead it dividing them into Number of subtasks where each subtask may
contain the records up to 4000.
Example:
If you need to make a field update of every record of account object in your organization, then we have
governing limits that would restrict us from achieving the above task.
Reason: In a single transaction we can process only 10,000 records. Now in the above case if we have
more than 10,000 records in the organization then we cannot perform this field update.
2. How can we schedule batch class to run in future only once from the specified minutes from current
time.
public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer
minutesFromNow)
or
public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer
minutesFromNow,Integer batchSize)
3.How to calculate the batch size if we are making any call out from the batch class execute method?
Basically in Salesforce we have limitation of 100 call outs for a transaction.When it comes to batch class
each execute method call will be considered as one transaction. So, in this case your batch size must be
calculated in such way
Batch size = (No of callouts allowed for single transaction /total number of call outs for each record) -
1;
Batch size = (100 /total number of call outs for each record) - 1;
4. How to stop all the running batches related to a particular batch classes before scheduling the same
batch class from the schedule class.
global class CaseCreationonSchedular implements Schedulable
{
global void execute(SchedulableContext SC)
{
}
YourBatchClassName cls = new YourBatchClassName();
DataBase.executeBatch(cls);
}
}
For this we can simply do this in the code so that at any given point of time you will have only schedule
job running for the same.
}
}
6.Why to use Batch class as we already having data loader to process the bulk data.
Agree with this point if and only if the data needs to be updated is static or predefined or which can be
done through excel.
We will choose batch class if we have to perform some custom calculations at run time or if you want to
run some complex logic which can't be driven by excel sheets in those cases we have to go with batch
classes.
Examples:
Do some relationship quires to update the data.
Make a call out to get the some information related to each record.
7.How many times the execute method will be executed to process the 1234 records.
It depends on your batch size what you have configured at the time of calling the batch class from
schedule class.
Execution method count = Total No Of Records/Batch Size (Any decimal ceil it to upper value)
If you haven't set any batch size then - 1234/200 = 6.17 = 7 times execute method will be called
12. What is the maximum number of batch classes allowed in Apex Flex Queue for execution?
100
……………………….
26) How do you debug the code in Apex?
A) In Apex, we have some tools for debugging. One of them is the system.debug() method, which prints
the value and output of the variable in the debug log.
There are two tools that you can debug:
Developer console
Debug log
34) Can you explain some string methods which were used in your projects?
A) I worked with various string methods in my previous projects, they are,
1) startsWith()- whether the string begins with a given string.
2) endsWith()- whether the string ends with a given string.
3) toUpperCase()- which is capitalized.
4) toLowerCase()- which is changed to lowercase.
5) length()- to find the length of the string.
6) replace()- replaces the string matching content.
7) split()- splits the string into a List collection according to the specified string.
8) trim()- remove the spaces before and after the string.
9) indexOf()- which gets the index of the first match of the string with the given string, and -1 if there is
no match.
10) lastIndexOf()- which gets the subscript of the last match of the string with the given string, and no.
11) substring()- intercepts the string between the given subscripts in the string.
35) Can you explain about few commonly used date type methods?
A) Date and DateTime methods are many, I will mention a few commonly used methods here,
1) newInstance(), create a Date.
E.g:
Date d = Date.newInstance(2019,1,15); //2019-1-15
2) day(), get the day of the date.
E.g:
Date d = Date.newInstance(2018,9,12);
d.day(); //12
3) month(), get the month in the date.
E.g:
Date d = Date.newInstance(2018,9,12);
d.month(); //9
4) year(), get the year in the date.
E.g:
Date d = Date.newInstance(2019,9,12);
d.year(); //2019
5) daysBetween(), get the number of days between the two dates.
E.g:
Date startDay = Date.newInstance(2018,9,12);
Date endDay =Date.newInstance(2018,10,2);
startDay.daysBetween(endDay); //20
6) addDays(), add the number of days.
E.g:
Date d = Date.newInstance(2018,9,12);
d.addDay(3); //2018-9-15
7) getTime(), which is the number of milliseconds elapsed from 1970-01-01 00:00:00 to the calculation
time.
E.g:
DateTime d = Date.newInstance(2018,9,12,8,0,0);
d.getTime(); //1473681600000
public class ContactTriggerHandler
{
}
Trigger:
{
if(ContactTriggerHandler.isFirstTime)
{
ContactTriggerHandler.isFirstTime = false;
for(Contact conObj : Trigger.New)
{
if(conObj.name != 'Test')
{
accIdSet.add(conObj.accountId);
}
}
} }
6. Too many Query rows:
Reason: The exception is being thrown because the maximum number of rows we can return in SOQL
calls in Apex is 50000.
Resolution: Limit the query results by adding limit. If you want to insert additionally, you will need to
use Batch Apex in which the 50K limit counts per batch execution. This limit Counts for each
transaction and these limits are reset for each execution of a batch of records in the execute method.
7. Error: System.ListException: List index out of bounds: 0
Reason: Our Query has returned no records that match the criteria. If you then attempt to access an
element at row 0, this will throw an error as that row doesn’t exist.
Resolution: Initially Always Check whether the list has records or not.
Error Code:
List<custom obj__c> lrecords=[select Id,name from custom obj__c ];
lrecords[0].Fileld1__c=2;
lrecords[0].Fileld2__c=3;
update lrecords;
Modified Code:
List<custom obj__c> lrecords=[select Id,name from custom obj__c ];
If(lrecords.size()>0)
{
lrecords [0].Fileld1__c=2;
lrecords[0].Fileld2__c=3;
update lrecords;
}
8. Error: Sobject row was retrieved via SOQL without querying the requested field:
Reason: This Error is caused by using the field that is not queried in the SOQL query.
Wrong Code:
Code: Id ids = ‘0012800001EOUIl’;
String Conname = c[0].Name;
System.Debug(‘@@@@’+c[0].id);
Id ids = ‘0012800001EOUIl’;
String Conname = c[0].Name;
System.Debug(‘@@@@’+c[0].id);
9. System.QueryException: List has no rows for assignment to SObject:
Reason: This error is caused when the query cannot get the results back.
Resolution:
Id ids = null’;
System.Debug(‘@@@@’+c.id);
Modified Code:
Id ids = ‘Null’;
If(ids!=Null)
{
System.Debug(‘@@@@’+c.id);
}
10. System.AsyncException: Rate Limiting Exception: AsyncApexExecutions Limit exceeded:
Reason: This error occurs when we are hitting an org-wide 24 hour rolling limit on asynchronous Apex.
The maximum number of asynchronous Apex method executions (batch Apex, future methods,
Queueable Apex, and scheduled Apex) per a 24-hour period: 250,000 or the number of user licenses in
your organization multiplied by 200– whichever is greater”.
11. System.AsyncException: Maximum callout depth has been reached:
Reason: Queueable Apex Limits
The execution of a queued job counts against the shared limit for asynchronous Apex method
executions.
Resolution:
You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
No limit is enforced on the depth of chained jobs, which means that you can chain one job to
another job and repeat this process with each new child job to link it to a new child job. For Developer
Edition and Trial organizations, the maximum stack depth for chained jobs is 5, which means that you
can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent
queueable job.
When chaining jobs, you can add only one job from an executing job with System.enqueueJob,
which means that only one child job can exist for each parent queueable job. Starting multiple child jobs
from the same queueable job isn’t supported.
12.System.DmlException: Insert failed. First exception on
row2; firsterrorINSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on
cross-reference id: []:
Reason: This error normally happens when a DML operation is performed with a wrong record Id.
14.Error: Invalid Data.: Apex trigger Acc caused an unexpected exception, contact your
administrator: Acc: execution of AfterInsert caused by: System.DmlException: Insert failed. First
exception on row 0 with id 0032800000vimdqAAA; first
error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]: Trigger.Acc: line 11,
column 1:
Reason: While inserting a record in Trigger. the dml should be outside the for loop.
Sample Code:
This is the wrong code:
trigger Acc on Account (after insert) {
List<Contact> ListCont =New List<Contact>();
for(Account acnt : Trigger.New){
for(integer i=0;i<3;i++){
Contact Cont=new Contact();
cont.Lastname=acnt.name+'ContApex1';
cont.accountid=acnt.id;
ListCont.add(cont);
insert ListCont;
} } }
sample. Email =sample.Email__c;
}}
Modified Code:
trigger sample on Account (after insert) {
for (Account Acc: Acclist){
Acc.Email = Acc.Email__c;
}Update Acclist;}
for(Account acnt : Trigger.New)
{
for(integer i=0;i<3;i++)
{
Contact Cont=new Contact();
cont.accountid=acnt.id;
ListCont.add(cont);
}
}
Modified Code:
trigger Acc on Account (after insert) {
List<Contact> ListCont =New List<Contact>();
for(Account acnt : Trigger.New)
{
for(integer i=0;i<3;i++)
{
Contact Cont=new Contact();
cont.accountid=acnt.id;
ListCont.add(cont);
}
}
}
17. Error: Compile Error: Invalid foreign key relationship: Account.Site at line 15 column 12:
Reason: While assigning a field value, the Syntax should
be SobjectName.FieldName or SObjectName.method()
Sample Code (Error)
integer i = 0;
accountMap.put(acct.Name,acct);
Account newAccount = accountMap.get(oldAccount.Name);
i = newAccount.Site.length;
}
}
Modified Code:
integer i = 0;
accountMap.put(acct.Name,acct);
Account newAccount = accountMap.get(oldAccount.Name);
i = newAccount.Site.length();
}}
Matcher matcher;
Pattern pat;
if(acc.AccountNumber != null)
pat = Pattern.compile('[0-9]');
acc.Copy_Me__c = matcher.group();
acList.add(acc);
insert acList;// Error will flow here because we cannot do dml for the same record.