Apex is the object-oriented programming language used by Salesforce developers to write custom business logic. It’s similar to Java and tightly integrated with the Salesforce platform. In this tutorial, we’ll walk through Apex basics, how to define a class, and some beginner-friendly coding examples.
What is Apex?
Apex allows developers to:
- Automate processes behind the scenes (triggers, batch jobs)
- Create custom business logic (classes, methods)
- Integrate with external systems using web services
- Control database operations (SOQL, DML)
Writing Your First Apex Class
apexCopyEditpublic class HelloWorld {
public static void sayHello() {
System.debug('Hello, Salesforce Developer!');
}
}
public class HelloWorld
→ Defines a classpublic static void sayHello()
→ Method that prints a messageSystem.debug()
→ Logs output in the Developer Console
Calling Your Apex Class in Anonymous Window
You can run this using the Anonymous Window in Developer Console:
apexCopyEditHelloWorld.sayHello();
Example: Apex Class for Adding Two Numbers
apexCopyEditpublic class Calculator {
public static Integer addNumbers(Integer a, Integer b) {
return a + b;
}
}
Call it like this:
apexCopyEditInteger result = Calculator.addNumbers(10, 20);
System.debug('Result: ' + result);
Example: Apex Class with SOQL
apexCopyEditpublic class AccountFetcher {
public static void fetchAccounts() {
List<Account> accList = [SELECT Id, Name FROM Account LIMIT 5];
for (Account acc : accList) {
System.debug('Account: ' + acc.Name);
}
}
}
[SELECT ...]
is a SOQL query (Salesforce Object Query Language)List<Account>
holds multiple Account records
Best Practices
- Always bulkify your logic (handle many records)
- Avoid hard-coded values
- Use Try-Catch blocks for error handling
- Limit SOQL queries to stay within governor limits