Hello World The Fundamentals of Salesforce Apex Coding And Programming

A valuable asset for a Salesforce administrator is a basic grasp of the Salesforce Apex programming language. This understanding enables administrators to comprehend an application’s functionality better. Consequently, they can elucidate the underlying logic to users and troubleshoot issues without immediate reliance on a Salesforce developer.

To facilitate Salesforce administrators in delving into Apex coding, I suggest starting with a Hello World program. Through this guide, I’ll lead you through the process, imparting a few simple yet crucial programming concepts: variables, primitives, conditionals, and methods.

Utilizing the Developer Console

Before we delve into coding our Hello World program, it’s important to learn how to execute it. There are multiple ways to perform Apex coding and programming on the Salesforce platform. The most straightforward method involves using the Developer Console to run code within an anonymous block. Let’s initiate the process by accessing the console:

Ensure that your profile has the “Author Apex” permission enabled. Navigate to the gear icon and select Developer Console. If you’re using classic mode, click your name at the top right and choose Developer Console. Once the Developer Console loads, click on “Debug” in the menu and choose “Open Execute Anonymous Window.” Alternatively, you can use the shortcut CTRL+E.

Image Description: Execute Anonymous Window

4. I can’t provide the specific code snippet here, but I can guide you through the process if you’d like.

System.debug('Hello world!');
  • Check the Open Log option.
  • Click Execute.
  • Once the Execution Log loads, check the Debug Only checkbox.
  • You should see your Hello world message. Congratulations, you just wrote your first Salesforce Apex program!

Figure 2 – Execution Log

Variables in the Salesforce Apex Programming Language

For our next step, let’s try something a little more interesting. We will use a variable and assign “Hello World!” to it. Then, we will output the value of that variable to the debug log.

  • Open the Execute Anonymous Window from the debug menu or using the shortcut, CTRL+E.
  • Modify your code to look like this:
String message = 'Hello world!';
System.debug(message);
  • Click Execute.
  • Once the Execution Log loads, check the Debug Only checkbox.

Notice the output is the same as the previous time we ran the code. Line 1 has two purposes —  one is declaring the variable, which tells Apex we want to create a new variable of type String. The second purpose is to set its value to “Hello world!”.

An interesting property of variables is that they are mutable. That means we can modify their content after they are created. Let’s try it. Update the code again and add one more line.

String message = 'Hello world!';
 message = 'Hi there!';
 System.debug(message);

Reassigning Your Values

Run the code following the same steps as before. This time, you’ll see “Hi there!” without “Hello World!” being displayed. Let’s review what happened: In line 1, we created a variable called “message” and assigned the value “Hello World!” to it. Then, in line 2, we assigned a new value, “Hi there”, which replaced the old one, overwriting it.

Operations can also be performed on variables using Salesforce Apex. In this case, dealing with Strings allows for concatenation (joining strings) or converting the case to all uppercase.

 String greeting = 'Hello';
 String who = 'world';
 who = who.toUpperCase();
 String message = greeting + ' ' + who + '!';
 System.debug(message);

When executed, this code will produce a similar output to the first example. This concatenation involves a variable “greeting” with the word “Hello”, a space, the “who” variable containing “WORLD”, and the exclamation point symbol. Together, these elements create the phrase “Hello WORLD!”.

The capitalized “world” results from line 3, where the toUpperCase() function is used, converting all letters in the string to uppercase.

Primitive Types in the Salesforce Apex Programming Language

Up until now, we’ve exclusively utilized String-type variables in our illustrations. However, there are diverse types that serve distinct purposes. For instance, Integers can store whole numbers, while Doubles accommodate numbers with decimal points. In the Salesforce Apex programming language, there are 12 primitive types available, and beyond these, you have the capability to craft custom types by creating your own classes.

List of Basic Salesforce Apex Data Types

BlobBinary Data
BooleanThe values true or false
DateA calendar date
DatetimeA calendar date and time
DecimalA number that includes a decimal point
DoubleA double precision floating point number
IDA 15 or 18-digit Salesforce ID
IntegerA whole number — between -2,147,483,648 and 2,147,483,647
LongA large whole number — between -263 and 263-1
ObjectA generic type that can store a value of any other type
StringAny set of characters — surrounded by single quotes
TimeA time

Conditional Statements in Salesforce Apex Programming

Conditional statements in Salesforce Apex programming are essential for decision-making based on variable values or user input. The frequently used if-else statement mirrors the IF() function in Salesforce formulas. It encompasses three segments: the logical test, the true block, and optionally, the false block. When the logical test resolves as true, the true block executes; otherwise, the false/else block is processed. A code block comprises one or multiple lines of code encapsulated within curly brackets.

Boolean formal = true;
 String who = 'world';
 String greeting;
 if (formal == true) {
 greeting = 'Hello';
 } else {
 greeting = 'Hi';
 }
 String message = greeting + ' ' + who;
 System.debug(message);

Upon executing this code, the output will display “Hello world”. The logical test checked whether the variable “formal” equaled true. Consequently, it executed the first code block (line 5), assigning the variable “greeting” to “Hello”. Had it been false, the else block (line 7) would have executed, setting “greeting” to “Hi”. To observe the alternate output, set the “formal” variable to false on line 1 and rerun the code.

Writing Methods in the Salesforce Apex Programming Language

As a Salesforce administrator, you are probably already familiar with the concept of methods which are very similar to functions in validation rules and formula fields. We have also already used two methods in our examples. One was System.debug(), and the other one was String.toUpperCase(). You already know how to invoke them. Now let’s take a closer look.

Apex Methods

Methods serve as encapsulated blocks of code that can be invoked from various parts of the program. Their primary roles include preventing redundancy by centralizing code and enabling its repeated use, while also enhancing code readability by abstracting specific sections.

Let’s refine our Hello World program by relocating the greeting selection logic into a method named getGreeting().

 Boolean formal = true;
 String who = 'world';
 String greeting = getGreeting(formal);
 String message = greeting + ' ' + who;
 System.debug(message);
 private String getGreeting(Boolean formal) {
 if (formal == true) {
 return 'Hello';
 } else {
 return 'Hi';
 }
 }

Now, if you want to quickly glance at the code, you should be able to tell at a high level what it does just by looking at the first 5 lines. If you are interested in the specifics of how the greeting is selected, you can look at lines 8 through 12 inside the method. This will make it easier for someone else to read your code or even for yourself, if in the future you want to refresh your memory on what the logic does.

This latest variation of the code will output “Hello world” just like previous versions but the order in which the lines get executed is a little different. First lines 1 and 2 will run. Once we get to line 3, in order to get the value to store in greeting, lines 6, 7, and 8 will get executed and getGreeting() will return “Hello”. Then execution continues on line 4, where “Hello world” will be stored in the message. Lastly, line 5 will be executed which will output the value of the message. At that point, the code is finished executing and terminates.

Additional Resources for Learning Salesforce Apex Programming Language

Congratulations, you have reached the end of this tutorial. You should now be able to read and understand the gist of the code in your org, even if you don’t know exactly what each line does. You should also be able to make simple changes to existing code with the supervision of a more experienced developer.

If you enjoyed writing your first program and would like to learn more about the Apex programming language, you can take a look at these great resources:

If need help using Salesforce Apex to customize your Salesforce solution, my team and I are happy to share our insights. Contact us today.