Apex Basic Syntax
What is Apex?
Apex is a programming language like Java or Python, but it’s made especially for Salesforce. It lets developers add custom logic and features to Salesforce apps—like automatic emails, data checks, and custom workflows.
Think of Apex as the magic behind the curtain in a Salesforce app.
Why Learn Apex?
•It helps automate tasks (like sending alerts or calculating totals).
•It gives you full control over how data moves and behaves in Salesforce.
•It’s a must-know if you want to become a Salesforce Developer.
Basic Apex Syntax: The Building Blocks
1. Class and Method
Just like we organize our school notebooks by subjects, Apex organizes code into classes and methods.
apex
public class HelloWorld {
public static void sayHello() {
System.debug(‘Hello, world!’);
}
}
• public class HelloWorld — A class named HelloWorld that is open to everyone.
• public static void sayHello() — A method (a block of code) called sayHello.
• System.debug() — Prints something to the log (just like saying it out loud).
2. Variables and Data Types
Variables are like labeled jars where you store things.
apex
CopyEdit
String name = ‘Alice’;
Integer age = 12;
Boolean isStudent = true;
• String stores text.
• Integer stores whole numbers.
• Boolean stores true/false.
3. Conditional Statements (If/Else)
These help the code make decisions, like choosing between chocolate or vanilla.
apex
if (age < 18) {
System.debug(‘You are a minor.’);
} else {
System.debug(‘You are an adult.’);
4. Loops (Doing things over and over)
For loops repeat tasks a certain number of times.
apex
for (Integer i = 0; i < 5; i++) {
System.debug(‘Number: ‘ + i);
}
5. SOQL – Salesforce Object Query Language
This is how Apex talks to Salesforce’s database to get or update information.
apex
List<Account> accList = [SELECT Name FROM Account WHERE Industry = ‘Education’];
6. Triggers
Triggers are like automatic alarms that run Apex code when something happens (like adding or updating a record).
apex
trigger AccountTrigger on Account (before insert) {
for (Account acc : Trigger.new) {
acc.Name = acc.Name + ‘ – Verified’;
}
}
Tips to Remember
• Always start simple—test your code with System.debug() to see what’s happening.
• Use comments (// This is a comment) to explain your code.
• Use Apex in combination with Salesforce Admin tools like Flows and Validation Rules.