What is Apex?
Apex is an object-oriented programming language present on the Salesforce platform. The language allows programmers to execute and perform transactions to control statements on servers associated with Salesforce. The language uses syntax that is extremely similar to that of Java
What are the Best Practices in Apex sales force?
- Bulkify the Apex code
- Avoid SOQL & SOSL DML inside For Loop
- Querying Large Data Sets
- Use of Map of SObject
- Use of the limits Apex methods
- Avoid Hardcoding IDs
- Use Database methods while using DML Operation
- Exception Handling in Apex code
- Write one trigger per Object per event
- Use Asynchronous Apex
What are the Sales force Apex Programming language features?
- It Offers DML with built exception handling
- SOQL & SOSL are used to retrieve the data
- Apex sales force has in built record locking mechanism. This will prevent record update conflicts
- It will run based on multi tenant environment
- Apex code is stored in meta data format
- It has syntax and variables similar to Java
- It will provide Unit Testing and Test execution with code coverage
- We can able to add web and email services in your application
- It is used to perform complex business processes
- We can add complex validation rules to your application
- It can be used to add a custom logic on operations like saving a record.
What are the ways to call the Apex class?
Below mentioned are the ways in Salesforce to call Apex class.
- From another class
- From developer console
- From JavaScript links
- From home page components
- By using trigger
- From VisualForce page
What types of statements we can use in Apex?
Apex must end with a semicolon ( ; ) it can be one of the following types:
- Assignment, such as assignment to a variable
- Condition (if-else)
- Loop: Do-While, While, For
- Locking
- Data manipulation language (DML)
- Transaction control
- Method call
- Exception handling (try catch)
How Many ways to write Apex Programming?
1.Standard Navigation
2.Developer Console
3.Execute Anonymous Window
4.Eclipse IDE
How Many ways to Execute an Apex Programming?
1.By using Execute Anonymous Window
2.By Using Triggers
3.By Using Visual force Pages
4.By Using Batch Apex
5.By Using Schedule Programming
6.By Using Email Services
7.By Using API / Web Services
How Does Apex work?
⇨All apex runs entirely on demand requirement on the lightning platform. Developers write and save apex code to the platform, and end users triggers execution of the Apex code via UI.
Apex is compiled, run and stored entirely on the Lighting Platform.
What is Developer Console?
- It is Integrated Development Environment(IDE)
- It is a collection of tools to create, test, debug applications in sales force org.
What are the Tasks supported by Developer Console?
- Writing code
- Compiling Code
- Debugging
- Testing
- Checking Performance
- SOQL queries
- color coding and auto complete
What are the other IDE or code editors you use as a sales force developer?
- Visual Studio Code
- Eclipse force.com IDE
- Welkin suite paid
Note: we can write maximum of 60,00,000 of apex characters code inside the organization.
Comment Lines will not consider apex characters
Apex Programming Execution Life Cycle?
- Each apex program code should get compiled using “Apex Compiler”. Will get executed with the help of a runtime engine called as “Apex Run time Engine”.
- Compiled Apex classes, visual force pages, triggers, batch classes, schedule classes, Web services, API’s will get resides inside the “Metadata Repository”
- We can track the result of the application inside “Debug log File”
- Debug log file contains the complete history of the application execution.
It describes the below information
1. The number of characters of code executed
2. Number of bytes of memory consumed while execution.
3. How much sales force server CPU cycle time has been used
4. How many SOQL queries has been invoked
5. How many DML statements has been executed
6. How many SOSL queries has been executed
7. How many Email notifications has been sent to the people
8. How many web service call outs has been invoked
9. Errors has been occurred while execution (I.e., Run time errors)
10. Application result (Result of the program)
Note: Apex provides a set of fundamental building block / features to be used to write the apex programming code
What is Variables?
- Variables is Nothing but a 'Name'. We are allocating the memory storage for assigning any 'variable value'.
- It is used to store the values 'Temporarily', while during the application execution.
While storing the values inside the variable, we have to define the variable first as below
Syntax:
[Access Specifier] <Datatype> <variableName> [=<Value>];
While assigning the variable, if the user didn’t assign any value, then apex will store the default value as “NULL” for each variable.
We can define the variables of same data type in a single statement as below.
1. VariableName should be always starts with a Character.
2. VariableName name should be a single word always. (It can have one special character "_")
3. We can't define two variables Name with the same name.
Ex: Integer customerCode, customerAge;
String customerName, designation, mailingAddress;
Date birthDate, joiningDate;
Decimal balanceAmount;
Assigning the values:
Once the variable has been assigned or defined, the user can assign the required value to the variable as below.
Syntax: <variableName> = <value>;
Integer customerCode = 348348234;
Integer customerAge = 32;
String customerName = ‘subbareddy’;
Note: While Assigning any value particular variable, this called as "Declaring Variable" as like below
String strName = 'My String'; //String variable declaration
Integer myInteger = 1; //Integer variable declaration
Boolean mtBoolean = true; //Boolean variable declaration
Note: Apex variables are Case-Insensitive
Integer m = 100;
for (Integer i = 0; i<10; i++) {
integer m = 1; //This statement will throw an error as m is being declared
again
System.debug('This code will throw error');
}
How Many DataTypes in sales force Apex?
DataType Describes the following features
- What type of data variable can hold or storing
- How much memory is required to store the data.
Apex programming provides the below 2 categories of Data Types
1.Primitive DataType: Integer, Long, string, Decimal, Double, Boolean, Date, DateTime, ID, Blob.
- These are the fundamental or basic datatypes offered by the Apex Programming language. Which contains the fixed length of memory.
- Which supports the Static memory allocation. All Primitive datatype values will get resides in "Stack" memory
- Note: Primitive datatypes causes the memory wastage.
- These are the fundamental/ basic data types offered by the apex programming language.
2.SObject DataType: Account, Contact, Lead, Opportunity, Case, Solution, Position C, Customer C, etc..
- SObject = Sales force Objects (Standard Objects + Custom Objects)
- By Using SObject data type we can store the sales force objects records inside the variable.
Note:
1. All SObject datatypes will supports Dynamic Memory allocation. (i.e., memory will be allocated dynamically at runtime of the application.)
2. SObject datatype values will get resides in the "Heap Memory".
What is SObject in Apex?
This is a special data type in Salesforce. It is similar to a table in SQL and contains fields similar to those in SQL. There are two types of SObject : Standard and Custom.
What is Operators in sales force Apex?
- Operator is nothing but a "Symbol", which performs the operations on the operands.
- Apex provides the below 5 categories of operators
1. Arithmetic Operators / Mathematical Operators
Ex: + --> Addition.
- --> Subtraction
* --> Multiplication
/ --> Division
Math.Mod() --> To get the Reminder value.
2. Relational Operators/ Comparison Operators
Ex:
<
>
<=
>=
== -> To check the equality of two numbers (Text Comparison)
!=
Equals () -> Which uses the “Binary Comparison”
3. Logical Operators
Ex:
AND (&&)
OR (||)
NOT (!)
4. Increment / Decrement Operators
++ ----> Increment the value by 1
Ex: Integer customerCode = 500501;
CustomerCode++; -------->500502.
-- ----->Decrement the value 1
Ex: Integer customerAge = 32;
CustomerAge--; ----->31.
5. Assignment Operators
=
+=
-=
*=
/=
Ex: Integer balanceAmount = 2500;
BalanceAmount += 5000;
What is Class in sales force Apex?
- A Class is Nothing but physical entity / Blue Print, It will Contains a Collection of Variables, Functions, Procedures, Properties, Constructors, etc...
- A Classes are used to achieve the encapsulation feature of OOPs Concept.
Note:
- Class name should always start with 'Character'.
- Class Name should be 'Single Word'
- We can't define two classes with same name in the application.
- As a best practice class name should starts with always "Capital letter"
- It should compiled and stored into the "Meta Data Repository" in Force.com platform.
What is Object?
- In-order to assign and access the class members, we need a reference called as an "Object".
- Which is an instance of the class.
Note:
- We can have one or more number of objects per a class.
- Each object should have a unique name. (i.e. we can't define two objects with the same name.)
- Each object holds the values for the class members.
- Each object contains its own memory location
What is Abstraction?
- Hiding internal details and showing functionality is known as "Abstraction".
- we use abstract class and interface to achieve abstraction.
- Different levels of hiding the Programming Elements (Variables and Methods)
Keywords:
private
protected
public
global
What are available "Access Modifiers" in sales force apex?
Private: If you Declare a One Class is Private, only we can use inside apex class in which they are defined. When you won't specify any, then default it will take 'Private' access modifier.
Public: If you declare One Class is Public, We can use entire application and also it will be available.
Public access modifier is not like Java Public. In that case you have to use 'Global'.
Global: If you declare One Class is Global, This Class is visible all Apex applications in the application and outside application.
Note: If Class(Inner) and Method is declare as global then top level class also must be declared as global.
Protected: If you are using protected access modifier with a variable or method then, that method or variable is visible to any inner classes in the defining apex class and also visible to the classes that extend from the defining apex class. You can use this protected modifier with instance methods and member variables.
Note:
Private variables and methods can be accessed in a public method with in the class
Private variables and methods cannot be accessed outside the class
Static variables and methods can be accessed in non-static methods (with in the class)
Non static variables and methods cannot be accessed in static methods
Return type – if the method does not contain 'void' then it should return datatype (ex: int, object, list, set, map)
Syntax: public static List<Account> methodName()
{
List<Account>accList = [select id, Name from Account];
Return accList;
}
Note:
- If the class is not declared as with sharing or without sharing then the class is by default taken as Both inner classes and outer classes can be declared as with sharing.
- If inner class is declared as with sharing and top level class is declared as without sharing then by default entire context will run in with sharing context.
- If a class is not declared as with / without sharing and if this class is called by another class in which sharing is enforced then both the classes run with sharing.
- Outer class is declared as with sharing and inner class is declared as without sharing then inner class runs in without sharing context only. (inner classes don’t take the sharing properties from outer class).
- Virtual: if a class is declared with keyword virtual then this class be extended (inherited) or this class methods can be overridden by using a class called overridden
What is Keywords in sales force Apex?
- In Sales force Apex, a keyword refers to a special reserved word that has a specific meaning and purpose within the programming language.
- These keywords are predefined and cannot be used as identifiers for variables, classes, methods, or other custom elements in Apex code.
Some examples of Apex keywords include:
- "if" and "else" used for conditional statements
- "for" and "while" used for loops
- "public" and "private" used for access modifiers
- "class" and "interface" used for defining classes and interfaces
- "try" and "catch" used for exception handling
What is "Return" Keyword?
It will return a value from a method.
Example:
public String getName()
{
return 'Test' ;
}
What is "Static" Keyword?
- This Keyword defines a method / variable that is only initialized once and is associated with an (Outer) class and initialization code.
- We can call variables / methods by Class name directly. No need of Creating an instance of class.
Example:
public class OuterClass
{
// Associated with instance
// Initialization the code
}
What is "Final" Keyword?
- This keyword is used to Defines constants and methods that can’t be overridden.
- While using this keyword we can't able to change after declare and assigning the values
Example:
public class myCls
{
static final Integer INT_CONST = 10;
}
Note: If you try to override the value for this INT_CONST variable, then you will get an exception – System.FinalException: Final variable has already been initialized.
What is "This" keyword?
This keyword refers to the current instance of the class.
Example:
public class MyClass
{
private String myVar;
public void setMyVar(String newValue)
{
this.myVar = newValue; // Use "this" to refer to the instance variable
}
}
What is "Super" keyword?
This keyword refers to the parent class of the current class.
Example:
public class ParentClass
{
public void display()
{
System.debug('This is the parent class.');
}
}
public class ChildClass extends ParentClass
{
public void display()
{
super.display(); // Call the display method of the parent class using "super"
System.debug('This is the child class.');
}
}
// Example usage Execute Window
ChildClass child = new ChildClass();
child.display();
What is "Null" keyword?
- This keyword is used to represent the value is 'Null'.
- It is typically used to indicate that a variable or object does not currently reference any value or object.
Example:
// Define a variable that can hold a string
String myString;
// Assign a value to the variable
myString = 'Hello World!';
// Output the value of the variable to the debug log
System.debug(myString);
// Set the variable to null
myString = null;
// Output the value of the variable to the debug log again
System.debug(myString);
What is "Abstract" keyword?
- Apex, the "abstract" keyword is used to define an abstract class or method.
- An abstract class or method is a class or method that is declared, but not implemented.
- It provides a template for other classes to extend or implement.
Example:
// Define an abstract class
public abstract class Animal
{
public abstract void makeSound();
}
// Define a class that extends the abstract class
public class Dog extends Animal
{
public void makeSound()
{
System.debug('Woof!');
}
}
// Define another class that extends the abstract class
public class Cat extends Animal
{
public void makeSound()
{
System.debug('Meow!');
}
}
// Example usage
Animal animal1 = new Dog();
animal1.makeSound();
Animal animal2 = new Cat();
animal2.makeSound();
What is "Extends" Keyword?
Defines a class that extents another class.
What is "Implements" Keyword?
This keyword is used declare a class that impediments an interface.
Example:
// Define an interface
public interface Animal
{
void makeSound();
}
// Define a class that implements the interface
public class Dog implements Animal
{
public void makeSound()
{
System.debug('Woof!');
}
}
// Define another class that implements the interface
public class Cat implements Animal
{
public void makeSound()
{
System.debug('Meow!');
}
}
// Example usage
Animal animal1 = new Dog();
animal1.makeSound();
Animal animal2 = new Cat();
animal2.makeSound();
What is "With Sharing" Keyword?
- Apex, the "with sharing" keyword is used to enforce sharing rules for a class.
- When a class is marked with the "with sharing" keyword, the sharing rules for the current user are enforced when accessing or modifying data
Example:
public with sharing class MyController
{
public List<Account> get Accounts()
{
return [SELECT Id, Name FROM Account];
}
}
This means that the user will only be able to see Accounts that they have access to based on their profile, role, sharing rules, etc.
What is "With Out Sharing" Keyword?
- Apex, the "without sharing" keyword is used to bypass sharing rules for a class.
- When a class is marked with the "without sharing" keyword, sharing rules are not enforced when accessing or modifying data.
Example:
public without sharing class MyController
{
public List<Account> getAccounts()
{
return [SELECT Id, Name FROM Account];
}
}
This means that the user will be able to see all Accounts in the database, regardless of their profile, role, sharing rules, etc.
What is "OutPut" Statements in sales force Apex?
It is used to Display or Output a value or message to the user.
The most commonly used output statements in Apex are "System.debug()" and "System.debug(LoggingLevel)".
Example:
System.debug(): This statement is used to display debug information in the Debug Log. It is useful for debugging code and verifying that it is working correctly.
Integer myNum = 5;
System.debug('The value of myNum is: ' + myNum);
OutPut: The value of myNum is: 5
System.debug(LoggingLevel): This statement is similar to System.debug() but allows you to specify the logging level.
The available logging levels are: NONE, ERROR, WARN, INFO, DEBUG, and FINE.
String myString = 'Hello World!';
System.debug(LoggingLevel.INFO, 'The value of myString is: ' + myString);
OutPut: 12:34:56.789 (123456789)|USER_INFO|[EXTERNAL]|INFO|The value of myString is: Hello World!
System.debug() with variables: This statement can be used to output the values of multiple variables.
Integer myNum = 5;
String myString = 'Hello World!';
Boolean myBool = true;
System.debug('myNum: ' + myNum + ', myString: ' + myString + ', myBool: ' + myBool);
OutPut: myNum: 5, myString: Hello World!, myBool: true
System.debug() in a loop: This statement can be used to output values in a loop.
List<Integer> myList = new List<Integer>{1, 2, 3, 4, 5};
for(Integer i : myList)
{
System.debug('The value of i is: ' + i);
}
OutPut: The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5
What is "Exceptions or Run Time Errors" in sales force Apex?
Whenever we are performing some operations some unexpected things will be happened, these are called as “Exceptions”.
What is "Debug Logs" in sales force apex?
- Debug logs are system log that keep track of data on how code & procedures are carried out on the Sales force platform.
- Developers can use debug logs to identify problems, troubleshoot them & optimize system behavior.
- Debug logs provide information on any failures or exceptions that take place during execution of a specific transaction or operation, including information about any errors or exceptions that occur.
What are the Exceptions we are facing in sales force Debug Log Files?
𝐀𝐩𝐞𝐱 𝐂𝐏𝐔 𝐭𝐢𝐦𝐞 𝐥𝐢𝐦𝐢𝐭 𝐞𝐱𝐜𝐞𝐞𝐝𝐞𝐝: This exception occurs when the Apex code exceeds the maximum CPU time allowed for a single transaction
𝐒𝐲𝐬𝐭𝐞𝐦.𝐐𝐮𝐞𝐫𝐲𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when a query executed in Apex returns no records or too many records. It may occur when the query user is trying to execute is having some issue.
𝐒𝐲𝐬𝐭𝐞𝐦.𝐍𝐮𝐥𝐥𝐏𝐨𝐢𝐧𝐭𝐞𝐫𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when an attempt is made to reference a null object. For example if a variable is not initialized and we are trying to access it in a method then this exception will occur.
𝐒𝐲𝐬𝐭𝐞𝐦.𝐋𝐢𝐬𝐭𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when an operation is performed on a list that is empty or when the element is not present on the mentioned index of the list
𝐒𝐲𝐬𝐭𝐞𝐦.𝐃𝐦𝐥𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when a DML operation (such as insert, update, or delete) fails in Apex.
𝐒𝐲𝐬𝐭𝐞𝐦.𝐌𝐚𝐭𝐡𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when a mathematical operation fails
𝐒𝐲𝐬𝐭𝐞𝐦.𝐍𝐨𝐀𝐜𝐜𝐞𝐬𝐬𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when a user does not have the appropriate permissions to access a specific resource in Sales force
𝐒𝐲𝐬𝐭𝐞𝐦.𝐓𝐲𝐩𝐞𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when a data type conversion fails in Apex. For example if an attempt is made to assign a value of one data type to a variable of a different data type, this exception may be thrown.
𝐒𝐲𝐬𝐭𝐞𝐦.𝐂𝐚𝐥𝐥𝐨𝐮𝐭𝐄𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧: This exception occurs when an error occurs while making a callout from Apex.
InvalidParameterValueException: This exception is thrown when a method is called with an invalid parameter value.
InvalidStateException: This exception is thrown when a method is called in an invalid state, such as trying to modify a read-only record.
CustomException: This is a custom exception that can be defined by the developer to handle specific error conditions in the code.
AuraHandledException: This exception is thrown in Lightning components when an error occurs during server-side processing.
Visualforce exceptions: These exceptions occur when there is an error in a Visualforce page, component, or controller.
Apex governor limit exceptions: These exceptions occur when the governor limits are exceeded while executing an Apex code block.
Assertion exceptions: These exceptions occur when an assertion fails during the execution of an Apex code block.
SOQL exceptions: These exceptions occur when there is an error in a SOQL (Sales force Object Query Language) statement.
What is Exception Handling - try, catch, finally, throw?
Exception occurs during the execution of program, we have to handle the excretion in code
try: This keyword is used to identifies a block of code in which an exception can occur.
catch: This keyword is used to identifies a block of code that can handle a particular type of exception.
finally: This keyword is used to identifies a block of code that is guaranteed to execute.
throw: This keyword is used to throws an exception, signaling that an error has occurred
What are the ways to overcome exception Handling?
While we are getting Exceptions or Run Time Errors, we are handling Two ways available.
1. Conditional Statements:
- Conditional statements are used to add one / more conditions to be get verified before executing the statements.
- If the conditions are satisfied, then statement will execute.
- If the conditions are not satisfied, then statement will skip the execution of statements.
- By Using Conditional Statements, we can change the control flow of the Application execution.
1. IF Condition
2. Switch Condition
3. Ternary Operators( ?: )
2. Exception Handling Mechanism
What is "Synchronous" Keyword?
The keyword "Synchronous" is used to specify that a particular operation or method call should be executed in a synchronous manner.
This means that the code will wait for the operation to complete before moving on to the next line of code.
public class ExampleClass
{
// This method will be executed synchronously
public static void synchronousMethod()
{
// Perform some synchronous operation here
}
// This method will be executed asynchronously
@future
public static void asynchronousMethod()
{
// Perform some asynchronous operation here
}
}
What is "Asynchronous" Keyword?
- Apex, the keyword "asynchronous" is used to specify that a particular method or operation should be executed asynchronously.
- This means that the code will not wait for the operation to complete before moving on to the next line of code.
- Asynchronous operations are typically used for long-running or resource-intensive tasks that might otherwise block the main thread of execution, such as sending emails, performing database operations, or making external web service calls.
What is "Static" and "Non-Static" Keyword?
In Sales force Apex, "static" and "non-static" are keywords used to define the scope and behavior of variables, methods, and classes.
The main differences between static and non-static in Sales force Apex are:
Scope: Static variables, methods, and classes can be accessed without the need for an instance of the class, while non-static variables, methods, and classes require an instance of the class to be created before they can be accessed.
Sharing of data: Static variables and methods are shared across all instances of a class and can be accessed by any code that has visibility to the class. Non-static variables and methods are unique to each instance of a class and can only be accessed by code that has a reference to that instance.
Initialization: Static variables are initialized when the class is first loaded into memory, while non-static variables are initialized when an instance of the class is created.
Memory usage: Static variables and methods use a single instance of memory throughout the lifetime of the application, while non-static variables and methods use separate instances of memory for each instance of the class that is created.
Example:
public class ExampleClass
{
// Static variable - shared across all instances of the class
public static Integer staticVar = 0;
// Non-static variable - unique to each instance of the class
public Integer nonStaticVar = 0;
// Static method - can be called without an instance of the class
public static void staticMethod()
{
// Perform some static operation here
}
// Non-static method - requires an instance of the class to be created
public void nonStaticMethod()
{
// Perform some non-static operation here
}
}
What is "Setter" method in sales force apex?
- This will take the value from the visual force page and stores to the Apex variable name.
- Apex, a setter method is a method that is used to set the value of a private or protected variable in a class.
- Setter methods are commonly used in conjunction with getter methods to provide controlled access to class variables.
Example:
public class ExampleClass
{
// Private variable
private Integer myVar;
// Setter method for myVar
public void setMyVar(Integer val)
{
myVar = val;
}
// Getter method for myVar
public Integer getMyVar()
{
return myVar;
}
}
Execution:
ExampleClass ex = new ExampleClass();
ex.setMyVar(10); // Sets the value of myVar to 10
Integer val = ex.getMyVar(); // Gets the value of myVar (val will be 10)
What is "Getter" Method?
This method will return a value to a visual force page whenever a name variable is called "Getter" Method.