Your First Apex Code
Anonymous Apex is code that runs once without being saved — perfect for experiments, data fixes, and learning.
4.1 Execute Anonymous
Anonymous Apex is code that runs once without being saved — perfect for experiments, data fixes, and learning. Open the Developer Console → Debug → Open Execute Anonymous Window, or put code in scripts/apex/hello.apex and run it from VS Code or the CLI:
Anonymous Apex runs as the current user, respects that user's sharing rules, can perform DML (changes are committed!), and is subject to the same governor limits as any synchronous transaction.
// scripts/apex/hello.apex
String greeting = 'Hello, Apex!';
System.debug(greeting);
Integer total = 0;
for (Integer i = 1; i <= 10; i++) {
total += i;
}
System.debug('Sum of 1..10 = ' + total); // 55sf apex run --file scripts/apex/hello.apex4.2 Your first class
Deploy it, then call it from Execute Anonymous:
// force-app/main/default/classes/HelloWorld.cls
public with sharing class HelloWorld {
// a static method — called on the class itself
public static String greet(String name) {
if (String.isBlank(name)) {
return 'Hello, World!';
}
return 'Hello, ' + name + '!';
}
}System.debug(HelloWorld.greet('Ada')); // Hello, Ada!
System.debug(HelloWorld.greet(null)); // Hello, World!4.3 Your first data operation
// create, query, update, delete — the full lifecycle
Account acc = new Account(Name = 'Apex Academy', Industry = 'Education');
insert acc; // DML: acc.Id is now populated
System.debug('New Id: ' + acc.Id);
Account fetched = [SELECT Id, Name, Industry FROM Account WHERE Id = :acc.Id];
fetched.Industry = 'Technology';
update fetched;
delete fetched; // goes to the Recycle Bin4.4 Your first test
Production deployments require tests. Every class should have one:
@isTest
private class HelloWorldTest {
@isTest
static void greetsByName() {
Assert.areEqual('Hello, Ada!', HelloWorld.greet('Ada'));
}
@isTest
static void greetsWorldWhenBlank() {
Assert.areEqual('Hello, World!', HelloWorld.greet(' '));
}
}sf apex run test --class-names HelloWorldTest --result-format human --code-coverage --wait 104.5 Comments and statements
// single-line comment
/* multi-line
comment */
/**
* ApexDoc comment — documents classes and methods.
* @param name the person to greet
* @return the greeting
*/
Integer x = 5; // statements end with semicolons; blocks use { }