What is a variable in Apex?

What is a variable in Apex? There are a lot of articles on the internet about Apex programming in Salesforce. However, almost none of them are written for Admins who want to transition to Salesforce programming or people who are only getting started with programming. This series of articles aims to explain the most basic concepts of programming in Salesforce Apex.

We will start with fundamentals that apply to all programming languages. But because Apex is highly wired into the Salesforce platform, we will of course discuss everything within that context.

While you could read an official Salesforce guide for every topic, let’s be honest: They aren’t written for people who want to learn how to code. They’re written for Computer Science nerds like myself. And they’re insanely boring :).

What is a variable in Apex?

Let’s start with the most basic concept: variables. A variable is just a box. You can put something in the box, and you can write a name on the box. Let’s name this box “books” and put books inside. We just created a variable with a name and type.

basics of apex merged 5

Of course, we don’t use any boxes in Apex. Here’s how we write a variable in Apex:

String books = 'Harry Potter';

We can see the three main components of a variable here: a type, name and value.

basics of apex merged 1 1

It’s very much like a box. We have a container of a certain type where we put some values. We can put different values into the variable as well.

Now, for a “real” definition of a variable: It’s a memory location of a specific type that holds a value.

Variable type

A variable type in Apex can be one of these things: a Class, Salesforce Object, Data Structure or Apex Type. Yeah, this opens a whole other can of worms. We will truly understand what a data type is in Apex after we discuss classes and objects.

Variable name

For the name of a variable, you can use anything besides reserved keywords.

Declare & initialize a variable

Every time you create a variable in Apex, there are two phases: declaration and initialization.

What is a variable in Apex?
What is a variable in Apex?

The first phase is called “declaration,” and it’s simply when you give a name and type to the variable. This phase is mandatory for creating a variable.

In the second phase, you actually give a value to your variable. It’s very much like putting books into a box. Your variable will keep this value until you change it—and you can change it as frequently as you want.

Here’s how it looks in code:

basics of apex merged 3 1

You have both phases in the same line. However, that’s not necessary. We can break them down into two lines or even just declare a variable without initializing it.

String books; // Here, the variable is declared but not initialized.
books = 'Harry Potter'; // The variable is initialized, but we could omit this line.

Or you can even overwrite the value that you saved into the variable at some point.

String books;
books = 'Harry Potter';
books = 'A song of ice and fire'; // now there is a new value of the variable

Type = value

If there is one thing that I want you to learn from this article, it’s this: type on declaration = type on initialization. Whenever you create a variable, ask yourself, “Is the right-side type equal to the type on the left side?” If your answer is yes, then the syntax is probably correct.

basics of apex merged 4 1

For example, the following will show an error in Apex:

String variable1 = 24;
Integer variable2 = '24';
Integer variable3 = true;
Boolean variable4 = 'false';

String variables

The first type is “String.” In string variables, we usually save everything that can be seen as a text. For example, the name, status, email or picklist value. To create a string, we need to enclose the value into single quotation marks (‘’). For example:

String name = 'Alex';
String oppStatus = 'Closed Won';
String email = 'alex@mail.com';

Integer & Decimal variables

An Integer variable obviously means there are integer numbers. There are limits to how big of a number we can save to the integer variable. That’s never a problem, though, because you won’t face such numbers in real life.

There is also a Decimal data type. The difference is that in the decimal variables, we can save values with the decimal places. And of course, we can save integers into decimal variables as well, but not vice versa. Here are some examples:

Integer a = 3;
Decimal aDec = 3.0;
Integer five = 5;
Decimal fiveDec = 5.0;
Ineteger zeroVariable = 0;
Decimal zeroVariableDec = 0.0;
Decimal pi = 3.14;
Decimal oneMoreVariable = 93.412;

Boolean variables

Boolean is an interesting variable type. We won’t be using this type directly very often, but it will be with us all the time in the control structures (e.g. if..else or loops).

The most important information to know about Boolean variables is that they can only hold one of three values: true, false, null. Think of Booleans as the checkboxes you know from the Salesforce UI.

The true power of Boolean variables lies in their operations, which we will discuss in the next unit, so the examples below aren’t that spectacular:

Boolean isTrue = true;
Boolean isFalse = false;

Date & DateTime variables

The Date data type is quite simple because you already know this data type from Salesforce. It corresponds completely with the field type “Date” in the Salesforce objects. The same is true for the DateTime data type.

Quite often, we use the date field to create today’s date. For now, you can just memorize how we do it. It will be clear after we discuss classes and methods. Here’s how we create it:

Date todayDate = System.today();
DateTime nowTime = System.now();

Id variables

Id variables can only contain ids of the records. Even though the syntax is similar to the string, they aren’t string. But keep this in mind: You can save every Id as string, but only Id can be saved as Id. Here are some valid examples of the code:

Id oppId = '00668000002XjVZAA0';
String oppId = '00668000002XjVZAA0';
Id accountId = '0016800000HWcfAAAT';

Null

What if we only declare a variable? The variable will have a special value called “null.” This just means “no value.” With that said, the null value is a bit annoying. Try to run the following code:

String name;
System.debug(name);

You will see this result in the debug logs:

bild1

So what’s the problem with the null variable? Let’s try to run this code:

String name;
System.debug(name.lenght());

You will get following error message:

System.NullPointerException: Attempt to de-reference a null object

OK, I know that looks scary, but it just says that we can’t run any operations on the null variable. That’s very annoying because we only get this error when we actually run the code. Therefore, sometimes we can’t spot the error while writing the code and the end user might get the error when running it. Imagine their surprise!

Variable question

Everyone wants to jump and create a trigger that makes an API call to the ERP system while firing a batch and parsing the Visualforce page into a PDF.

giphy 1

And then – oh wait, what exactly is a variable in Apex?

Let’s have a look at a simple example:

String name = 'Alex';

This is how it looks inside the memory

img1

The variable is just a pointer to the actual value. It contains only two pieces of information:

  1. Variable name
  2. Address of the value
img2

Let’s look at another example. Nothing too crazy, just a new variable!

String name = 'Alex';
String anotherName = 'John';
img3

Now, let’s do something mind-blowing, let’s re-assign one variable to another:

name = anotherName;
System.debug(name); // ???

What do you think will be printed out? That’s right, it will be “John”!

We assigned the value from “anotherName” to “name”, so they both now point to the same information.

img4

What happens to the “Alex” value in memory? It will be deleted by the Apex engine, as it’s not used anymore.

img5

 

<h4 class="item-title">admin</h4>

admin

Related Posts

blog images 12

SOQL in Apex

blog images 11

Loops in Apex

blog images 10

Lists in Apex

4 Comments

  • Anna Szabo May 27, 2023

    The teaching style of this writer is exceptional! So simple to understand, flows logically, it’s well-illustrated, and I just want to say 10000x “thank you!” This helps me prepare for my PD1 certification exam.

    • User Avatar
      admin May 28, 2023

      Good luck with PD1! Let me know once it’s done 🙂

  • Rupali July 28, 2023

    Great Contain

  • Fay Oates August 12, 2023

    Thank you for making it so simple and easily digestible. Learning Apex code for beginners can be incredibly intimidating.

Leave a Reply

Your email address will not be published. Required fields are marked *

t.me/ihor_igor

Subscribe for news about new courses or discounts.

No spam, we promise.


    © 2023 All Rights Reserved by site  igor@cloud-prism.com