Thursday, March 8, 2018

Usefull Salesforce Apex Interview Questions and Answers

1. What Is Apex ?

Answer: It is the in-house technology of salesforce.com which is similar to Java programming with object-oriented concepts and to write our own custom logic.
  • Apex is a procedural scripting language in discrete and executed by the Force.com platform.
  • It runs natively on the Salesforce servers, making it more powerful and faster than non-server code, such as JavaScript/AJAX.
  • It uses syntax that looks like Java.
  • Apex can written in triggers that act like database stored procedures.
  • Apex allows developers to attach business logic to the record save process.
  • It has built-in support for unit test creation and execution.
2. What are the advantages of using Batch Apex instead of a trigger ?
Answer: A Batch class allows you to define a single job that can be broken up into manageable chunks that will be processed separately.
If you have 10,001 Account records in your org, this is impossible without some way of breaking it up.
3. What is Apex provides built-in support for common Force.com platform idioms and What Apex is including ?
Answer:
  • Data manipulation language (DML) calls, such as INSERT, UPDATE, and DELETE, that include built-in Dml Exception handling
  • Inline Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL) queries that return lists of sObject records
  • Looping that allows for bulk processing of multiple records at a time
  • Locking syntax that prevents record update conflicts
  • Custom public Force.com API calls that can be built from stored Apex methods
  • Warnings and errors issued when a user tries to edit or delete a custom object or field that is referenced by Apex
Note: Apex is included in Unlimited Edition, Developer Edition, Enterprise Edition, and Database.com
4. What is difference between public and global class in Apex ?
Answer:
  • Public class can be accessed within application or namespace. This is not exactly like public modifier in Java.
  • Global class visible everywhere, any application or namespace. Web Service must be declared as Global and which can be accessed inside JavaScript also. It is like public modifier in Java.
5. What is Apex vs. Java: Commonalities ?
Answer: 
  • Both have classes, inheritance, polymorphism, and other common OOP features.
  • Both have the same name variable, expression, and looping syntax.
  • Both have the same block and conditional statement syntax.
  • Both use the same object, array, and comment notation.
  • Both are compiled, strongly-typed, and transactional.
6. What is Apex Pages ? Add Message ?
Answer: Apex Pages.add Message Add a message to the current page context. Use Apex Pages to add and check for messages associated with the current page, as well as to reference the current page. In addition, Apex Pages is used as a namespace for the Page reference and Message classes.
7. What is Apex vs. Java: Differences ?
Answer:
  • Apex runs in a multi-tenant environment and is very controlled in its invocation and governor limits.
  • To avoid confusion with case-insensitive SOQL queries, Apex is also case-insensitive.
  • Apex is on-demand and is compiled and executed in the cloud.
  • Apex is not a general-purpose programming language but is instead a proprietary language used for specific business logic functions.
  • Apex requires unit testing for development into a production environment.
8. How Validation Rules Executed ? Is It Page Layout / Visualforce Dependent ?
Answer:  The validation rules run at the data model level, so they are not affected by the UI. Any record that is saved in Salesforce will run through the validation rules.
9. Explain Considerations for Static keyword in Apex ?
Answer:
  • Apex classes cannot be static.
  • Static allowed only in outer class.
  • Static variables not transferred as a part of View State.
  • Static variables and static block run in the order in which they are written in class.
  • Static variables are static only in the scope of a request.
10. What Is The Difference Between Database.insert And Insert ?
Answer:  Insert is the DML statement which is same as databse.insert.
However; database.insert gives more flexibility like rollback, default assignment rules etc. We can achieve the database.insert behavior in insert by using the method setOptions(Database.DMLOptions)
Important Difference:
  • If we use the DML statement(insert), then in bulk operation if an error occurs, the execution will stop and Apex code throws an error which can be handled in try catch block.
  • If DML database methods(Database.insert) used, then if an error occurs the remaining records will be inserted/updated means partial DML operation will be done.
11. When I want to export data into SF from Apex Data Loader, which Option should be enable in Profile ?
Answer:  Enable API
12. What Is The Scope Of Static Variable ?
Answer: 
  • When you declare a method or variable as static, it’s initialized only once when a class is loaded. Static variables aren’t transmitted as part of the view state for a Visualforce page.
  • Static variables are only static within the scope of the request. They are not static across the server, or across the entire organization.
13. How To Write The “where” Clause In Soql When Group By Is Used ?
Answer: We cannot use the “Where” clause with Group By instead we will need to use the “Having Clause“.
Example:
Get all the opportunity where more than one record exists with same name and name contains “ABC”.
SELECT COUNT(Id) , Name FROM Opportunity GROUP BY Name Having COUNT(Id) > 1 AND Name like ‘%ABC%’
14. What Happens If Child Have Two Master Records And One Is Deleted ?
Answer: Child record will be deleted.
15. Explain few considerations for @Future annotation in Apex ?
Answer:
  • Method must be static
  • Cannot return anything ( Only Void )
  • To test @future methods, you should use startTest and stopTest to make it synchronous inside Test class.
  • A parameter to the @future method can only be primitive or collection of primitive data type.
  • Cannot be used inside VF in Constructor, Set or Get methods.
  • A @future method cannot call another @future method.
16. What Is Difference In Render, Rerender And Renderas Attributes Of Visualforce ?
Answer:
  • Render: It works like “display” property of CSS. Used to show or hide the element.
  • Rerender: After Ajax which component should be refreshed – available on command link, command button, action support etc.
  • Renderas: render page as pdf, doc and excel.
17. Explain Difference In Count() And Count(fieldname) In Soql ?
Answer:
COUNT()
  • COUNT() must be the only element in the SELECT list.
  • You can use COUNT() with a LIMIT clause.
  • You can’t use COUNT() with an ORDER BY clause. Use COUNT(fieldName) instead.
  • You can’t use COUNT() with a GROUP BY clause for API version 19.0 and later. Use COUNT(fieldName) instead.
COUNT(fieldName)
  • You can use COUNT(fieldName) with an ORDER BY clause.
  • You can use COUNT(fieldName) with a GROUP BY clause for API version 19.0 and later.
18. How To Get The List Of All Available Sobject In Salesforce Database Using Apex (dynamic Apex) ?
Answer: Map m = Schema.getGlobalDescribe();
19. What is batch apex ? Why do we use batch apex ?
Answer: A developer can now employ batch Apex to build complex, long-running processes on the Force.com platform. For example, a developer could build an archiving solution that runs on a nightly basis, looking for records past a certain date and adding them to an archive. Or a developer could build a data cleansing operation that goes through all Accounts and Opportunities on a nightly basis and updates them if necessary, based on custom criteria.
Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.
Batch Apex is exposed as an interface that must be implemented by the developer. Batch jobs can be programmatically invoked at runtime using Apex.
A need of Batch Apex: As you, all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows of objects it is very complex in salesforce and it does not allow you to operate on more than a certain number of records which satisfies the Governor limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
Salesforce has come up with a powerful concept called Batch Apex. Batch Apex allows you to handle a number of records and manipulates them by using a specific syntax.
We have to create a global apex class which extends Database. Batch able Interface because of which the salesforce compiler will know, this class incorporates batch jobs. Below is a sample class which is designed to delete all the records of Account object (Let us say your organization contains more than 50 thousand records and you want to mass delete all of them).
20. How To Get All The Fields Of Sobject Using Dynamic Apex ?
Answer:  Map m = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(‘API_Name_Of_SObject’) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map fields = r.fields.getMap();

21. What Is Property In Apex ? Explain With Advantages ?
Answer: Apex mainly consists of the syntax from the well-known programming language Java. As a practice of encapsulation in java we declare any variable as private and then create the setters and getters for that variable.
private String name;
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
However, the Apex introduced the new concept of property from language C# as shown below:
public String name {get; set;}
As we can see how simple the code is and instead of using nearly 8 to 11 lines all done in 1 line only. It will be very useful when lots of member is declared in Apex class. It has another advantage in “number of lines of code” limit by salesforce which will drastically reduced.
22. What are few limitations of Savepoint or Transaction Control in Apex ?
Answer:
  • Each savepoint you set counts against the governor limit for DML statements.
  • Static variables are not reverted during a rollback. If you try to run the trigger again, the static variables retain the values from the first run.
  • Each rollback counts against the governor limit for DML statements. You will receive a Runtime error if you try to rollback the database additional times.
  • The ID on an sObject inserted after setting a savepoint is not cleared after a rollback.
23. Explain The Need Or Importance Of The Controller Extension ?
Answer: Controller extension is very useful and important concept introduced by the salesforce recently. It gives the power to programmer to extend the functionality of existing custom controller or standard controller.
A Visualforce can have a single Custom controller or standard controller but many controller extensions.
We can say that the custom extension is the supporter of custom or standard controller.
Consider one example: If there is one controller written and used by the multiple visualforce pages and one of them needs some extra logic. Then instead of writing that logic to controller class (Which is used by many visualforce pages) we can create a controller extension and apply to that page only.
24. How To Force Lead Assignment Rule Via Apex While Updating Or Adding The Lead ?
Answer: To enforce Assignment Rules in Apex you will need to perform following steps:
  • Instantiate the “Database.DMLOptions” class.
  • Set the “useDefaultRule” property of “assignmentRuleHeader” to True.
  • Finally call a native method on your Lead called “setOptions”, with the Database. DMLOptions instance as the argument.
// to turn ON the Assignment Rules in Apex
Database.DMLOptions dmlOptn = new Database.DMLOptions();
dmlOptn.assignmentRuleHeader.useDefaultRule = true;
leadObj.setOptions(dmlOptn);
25. How To Read The Parameter Value From The Url In Apex ?
Answer: Consider that the parameter name is “RecordType”.
String recordType = Apexpages.currentPage().getParameters().get(‘RecordType’);
26. What are the recommended ways to refactor in Apex ?
Answer: I use the second method. After refactoring, I select the ‘src’ folder, use File Search/Replace and all the changes are made and saved to the server in one go.
27. If One Object In Salesforce Have 2 Triggers Which Runs “before Insert”. Is There Any Way To Control The Sequence Of Execution Of These Triggers ?
Answer: Salesforce.com has documented that trigger sequence cannot be predefined. As a best practice create one trigger per object and use comment blocks to separate different logic blocks. By having all logic in one trigger you may also be able to optimize on your SOQL queries.
28. What Is The Need Of “custom Controller” In Visualforce As Everything Can Be Done By The Combination Of Standard Controller + Extension Class ?
Answer: Sharing setting is applied on standard object/extension by default; In case we don’t want to apply sharing setting in our code then Custom control
It is possible that the functionality of page does not require any Standard object or may require more than one standard object, then, in that case, a Custom controller is required.
29. What Is The Difference Between Trigger.new And Trigger.old In Apex – Sfdc ?
Answer:
Trigger.new:
  • Returns a list of the new versions of the sObject records
  • Note that this sObject list is only available in insert and update triggers
  • i.e., Trigger.new is available in before insert, after insert, before update and after update
  • In Trigger.new the records can only be modified in before triggers.
Trigger.old:
  • Returns a list of the old versions of the sObject records
  • Note that this sObject list is only available in update and delete triggers.
  • i.e., Trigger.old is available in after insert, after update, before delete and after update.
30. Is there a defacto 3rd party utilities library for Apex such as Apache Commons is for Java ?
Answer: Apex-lang is about as close to a Java-style library as you can get. Contains several string, database, and collection utilities that mimmick Java functionality. Be aware though, some stuff including Comparing and Sorting collections is out of date with the advent of the Comparable interface in Apex. In addition to apex-lang, and like you suggest, I typically create or reuse static helper methods throughout my projects. Static helper methods are very convenient for reusing code in Chatter functionality, DML handling, Exception handling, Unit testing, etc.

31. How To Create Many To Many Relationships Between Object ?
Answer:
  • Creating Many to Many relationship in salesforce is little tricky. You cannot create this type of relationship directly. Follow below steps to create this type of relationship.
  • Create both objects which should be interlinked.
  • Create one custom object(also called as junction object), which should have auto number as unique identification and create two master relationships for both objects, no need create tab for this object.
  • Now on both objects, add this field as related list.
32. In Class Declaration If We Don’t Write Keyword “with Sharing” Then It Runs In System Mode Then Why Keyword “without Sharing” Is Introduced In Apex ?
Answer: Let’s take example, there is classA declared using “with sharing” and it calls classB method. ClassB is not declared with any keyword then by default “with sharing” will be applied to that class because originating call is done through classA. To avoid this we have to explicitly define classB with keyword “without sharing”.
33. In Which Sequence Trigger And Automation Rules Run In Salesforce.com ?
Answer: The following is the order salesforce logic is applied to a record.
  • Old record loaded from database (or initialized for new inserts)
  • New record values overwrite old values
  • System Validation Rules
  • All Apex “before” triggers (EE / UE only)
  • Custom Validation Rules
  • Record saved to database (but not committed)
  • Record reloaded from database
  • All Apex “after” triggers (EE / UE only)
  • Assignment rules
  • Auto-response rules
  • Workflow rules
  • Escalation rules
  • Parent Rollup Summary Formula value updated (if present)
  • Database commit
  • Post-commit logic (sending email)
Additional notes: There is no way to control the order of execution within each group above.
34. What is apex data loader ?
Answer: Apex data loader is used to insert, update, upsert, export the data. By using apex data loader we can import the data from outside the salesforce also.
35. What Is S-control ?
Answer: S-Controls are the predominant salesforce.com widgets which are completely based on Javascript. These are hosted by salesforce but executed at client side. S-Controls are superseded by Visualforce now. 

36. If User Doesn’t Have Any Right On Particular Record And Have Only Read Level Access At Object Level. Can He Change The Record Owner ?
Answer: Yes. In profile, there is setting for “Transfer Record”.
37. Will Visual Force Still Supports The Merge Fields Usage Like S-control?
Answer: Just like S-Controls, Visualforce Pages support embedded merge fields, like the {!$User.FirstName} used in the example.
38. In How Many Ways We Can Invoke The Apex Class ?
Answer:
  • Visualforce page
  • Trigger
  • Web Services
  • Email Services
39. What Are Merge Fields? Explain With Example ?
Answer: Merge fields are fields that we can put in Email templates, mail merge templates, custom link or formula fields to incorporate values from a record.
Example: {!CustomObject.FieldName__c}
40. In Which Scenario Share Object “mycustomobject__share” Is Not Available/created For Custom Object “mycustomobject” ?
Answer: The object’s organization-wide default access level must not be set to the most permissive access level. For custom Objects, that is Public Read/Write.

41. How To Schedule A Class In Apex ?
Answer: To invoke Apex classes to run at specific times, first implement the Schedulable interface for the class, then specify the schedule using either the Schedule Apex page in the Salesforce user interface, or the System.schedule method.
After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class.
Salesforce only adds the process to the queue at the scheduled time. Actual execution may be delayed based on service availability. The System.Schedule method uses the user’s time zone for the basis of all schedules. You can only have 25 classes scheduled at one time.
Example Code:
String CRON_EXP = ‘0 0 * * * ?’;
clsScheduledHourly sch = new clsScheduledHourly();
system.schedule(‘Hourly Sync’, CRON_EXP, sch);
42. What are the differences between static and non-static variables in Apex ?
Answer: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
43. What Are The Types Of Controller In Visualforce ?
Answer: There are basically two types of Controller in Visual force page:
  • Standard Controller
  • Custom Controller
44. Which SOQL statement can be used to get all records even from recycle bin or Achieved Activities ?
Answer: We will need “ALL Rows” clause of SOQL.
Sample : SELECT COUNT() FROM Contact WHERE AccountId = a.Id ALL ROWS Salesforce Apex Interview Questions and Answers
45. Explain System.runas() ?
Answer: Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account. The system method, System.runAs(), lets you write test methods that change user contexts to either an existing user or a new user. All of that user’s record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after all runAs() test methods complete.
Example :
System.runAs(u) {
// The following code runs as user ‘u’
System.debug(‘Current User: ‘ + UserInfo.getUserName());
System.debug(‘Current Profile: ‘ + UserInfo.getProfileId()); }
// Run some code that checks record sharing
}
46. How can you lock record using SOQL so that it cannot be modified by other user ?
Answer: we will need “FOR UPDATE” clause of SOQL.
Sample : Account [] accts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];
47. Explain Test.setpage() ?
Answer: It is used to set the context to current page, normally used for testing the visual force controller.
48. If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, What will happen to later savepoint variables ?
Answer: If you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
49. How To Round The Double To Two Decimal Places In Apex ?
Answer: Decimal d = 100/3;
Double ans = d.setScale(2);
50. What are few Considerations about Trigger ?
Answer:
  • Upsert triggers fire both before and after insert or before and after update triggers as appropriate.
  • Merge triggers fire both before and after delete triggers for the losing records and before update triggers for the winning record only.
  • Triggers that execute after a record has been undeleted only work with specific objects.
  • Field history is not recorded until the end of a trigger. If you query field history in a trigger, you will not see any history for the current transaction.
  • You can only use the webService keyword in a trigger when it is in a method defined as asynchronous; that is, when the method is defined with the @future keyword.
  • A trigger invoked by an insert, delete, or update of a recurring event or recurring task results in a runtime error when the trigger is called in bulk from the Force.com API.
  • Merge trigger doesn’t fire there own trigger instead they fire delete and update of loosing and winning records respectively.

1 comment :

dharani said...

Java is used to build large enterprise class applications. Java works great within corporate environments, or if you're building a very large scale system. Although it can be used for small tasks, it's less suited for that.
Java Training in Pune