Apex Basics: A Beginner's Guide to Salesforce Apex Programming
Introduction to Apex
If you’re new to Salesforce development, Apex is the programming language you need to learn first. It helps you add custom logic to Salesforce and automate things easily.
In this guide, we’ll start with Apex basics, understand its simple rules, and write our first Apex class step by step. Ultimately, you’ll get a small practice task to try on your own.
What is Apex?
Apex is a coding language used inside Salesforce. It’s similar to Java but works only in Salesforce. It helps in:
Automating things – Running code when something happens (like saving a record).
Adding custom logic – Making Salesforce work exactly how you want.
Working with data – Getting, saving, or changing records in Salesforce.
Connecting with other systems – Talking to outside services using APIs.
Key Features of Apex
Works in Salesforce’s Cloud – Runs on Salesforce servers.
Handles Salesforce Data – Can read and change Salesforce records.
Follows Rules (Governor Limits) – Stops one user from using too many resources.
Runs on Demand – Only runs when needed, saving resources.
Supports Queries & Updates – Can get and change data using special commands.
Your First Apex Class
Now, let’s write a simple Apex class to see how it looks.
public class HelloApex {
// A method that prints "Hello, Apex!"
public static void sayHello() {
System.debug('Hello, Apex!');
}
}
Breaking it Down:
public class HelloApex
→ Creates a class (like a container for code).public static void sayHello()
→ A method inside the class that does something.System.debug('Hello, Apex!');
→ Prints a message when the method runs.
Running Apex Code
To run this code:
Open Developer Console in Salesforce.
Click on Debug > Open Execute Anonymous Window.
Type the command below and press Execute:
HelloApex.sayHello();
- Go to Logs, and you will see "Hello, Apex!" printed.
Practice Task: Write Your First Apex Class
What You Need to Do:
Create an Apex class called
MyFirstClass
.Inside the class, create a method called
greetUser
.The method should print: "Welcome to Apex, [Your Name]!"
Run the method using Execute Anonymous.
Example Code (Try Writing it Yourself First!):
public class MyFirstClass {
public static void greetUser() {
System.debug('Welcome to Apex, John!');
}
}
To run it:
MyFirstClass.greetUser();