Variables and Data Types in Salesforce Apex

In Salesforce, Apex is a programming language used to work with the UI and data model in the org. Apex is designed to solve complex business logic that we cannot complete using a declarative approach.

In this tutorial, I will explain variables and data types in Salesforce Apex, as well as various data types and their uses. Additionally, we will see how to use data types to develop Apex code in Salesforce.

Variables in Salesforce

In Salesforce Apex, variables are named value holders. They store a particular value inside them, and whenever you access them, they return that particular value as a result.

Apex is a strongly typed programming language, meaning that every variable needs to be declared with a particular data type, which is the type of information it will store.

For example, if you want to store a number, create a variable with an Integer datatype.

Variables and Data Types in Salesforce Apex

Data Types in Salesforce Apex

Data type can be defined as a classification that specifies the type of data a variable can hold in a programming language.

It is the kind of values that can be stored and the operations that can be performed on that data. The syntax of Apex in Salesforce is similar to Java, and the data types that we use in Apex are identical.

1. Primitive Data Types in Salesforce Apex

The primitive data types in Salesforce Apex are the foundation for storing basic data values. They represent specific types of information and specify actions that can be performed on that data. All Apex variables, including class member variables and method variables, are set to null. Before using variables that you declared, ensure they are initialized to the appropriate values.

Here are examples of primitive data types:

1. Integer in Salesforce

It is used to store short numbers or non-fractional values within the -2117483648  to  +2117483647 range. This data type has another subtype, Long. The extended data type is used to store more extended numbers, which can store values from -2^63 to +2^63-1. If you need to store large numbers, you can use long data types.

Example of an Integer data type:

integer i = 50;
system.debug ('entered number is:' +i);

Example of Long Integer data type: Here, while declaring a long integer value to store the value, we have to specify L as a suffix, either capital or small; otherwise, you will get a compile-time error.

long no = 2145689464654L;
system.debug ('entered long number is:' +no);

2. Float Datatype in Salesforce

Apex does not use the float data type directly. For that, in Apex, we have two sub-types, Double and Decimal, which are used to store fractional values in decimals or points. In that case, we have to use the floating-point data type.

Double data type:

double d = 3.1423;
system.debug (d);

Decimal data type: Decimal is similar to double. It stores mainly the currency fields‘ values in our Salesforce objects. Using the decimal data type, we can perform multiple functions, like rounding off currency fields or performing different operations, as we cannot do with the double data type.

  • Decimal variable: Here, we declare a decimal variable and want to remove numbers after the decimal point.
  • round(): It is a function that converts a decimal to a whole number.
public class apexdemo {
    
    public static void demo(){
        
        decimal d = 2555.34;
        system.debug('before round off value is: '+d);
        
        //Rounding off decimal value
        long l = d.round();
        system.debug('after rounding off value of decimal variable: '+l);   
    }
}

Output:

3. Boolean Data Type in Salesforce

When you want to store information/output in the yes and no or True or False values, then we can use the Boolean data type in Salesforce Apex.

Boolean b = True;
Boolean b1 = False;
system.debug (b1);

4. String Data Type in Salesforce

In the apex, we have a string data type for when we want to store any alphanumeric character or string. On a string, we can perform multiple string functions that use string manipulation.

Here, you need to ensure the literal or value you are storing in the string is in single quotes, not double quotes, like in other programming languages.

String s = 'Salesforce Developer';
system.debug (s);

5. Date / Time / DateTime in Salesforce

In Salesforce Apex, we have a Date data type, which is divided into two subtypes: Time and DateTime. We can convert a string to a date_time, and there are multiple operations that we can perform on the date data type.

1. Date: Using the date data type, we can declare dates and have different functions, such as the current date and converting a date to time. However, we cannot assign a date value to a variable directly; for that, we have to use the static method of the Date class.

Date d = '2024-05-15' ;  //Error

Date d = Date.newInstance ( 2024,05,15 );
system.debug (d);

2. Time: For the time data type, we also need to use the static method, in that we need to enter the first hour, minute, second, and millisecond. For the time data type, we also have multiple methods that are used to perform operations in Apex.

Time t = Time.newInstance ( 11,25,30,35);
system.debug (t);

3. DateTime: The date_time data type we use to declare the date and time. Here also, we need to use the static method and pass the arguments as I have shown in the following syntax:

DateTime.newInstance (year, month, day, hour, min, sec, mili sec);

DateTime dt = DateTime.newInstance (2024, 5, 15, 2, 50, 30, 15);
system.debug (dt);

6. ID Data Type in Salesforce

In any other programming language, there is no variable or data type called an ID. In Salesforce Apex, we use the ID data type because it allows you to store a record ID.

When entering the ID value, it must be in string format, and we can specify both 15-digit and 18-digit IDs. If you specify the 15-digit ID, when it gets assigned to the variable, it will automatically get converted to the 18-digit record ID.

But if you try to or enter an invalid value into the ID variable, you will get a run-time exception whenever you try to execute that program.

ID i = '001J3000007VLpQ';
system.debug

7. Blob in Salesforce

The Blob stands for a binary large object. This data type is similar to the blob data type used in databases to store files.

In Salesforce Apex, when you want to store a binary object having binary data, in that case, we can use the blob data type.

Here, to store the information in a blob, first, you need to store all of the binary information into the string, and then you need to convert it to blob data type using the Blob.valueOf() with a string argument. Then, it will be stored in the blob data type.

String s = 'ifgrehgreoighfuiwe'
Blob b = Blob.valueOf (s);
              //OR
Blob b = Blob.valueOf ( 'ifgrehgreoighfuiwe');

If you want to convert that information again to the string, in that case you can use the toString() method.

system.debug ( b.toString);

These are the primitive data types that we use in Salesforce Apex.

2. sObject Data Type in Salesforce Apex

In other programming languages, we need first to establish a database connection with our database and then fetch the records. However, in Apex, we do not have to create a database connection with the Salesforce database. It is integrated with the database, allowing you to query records and import them into the sObject.

sObjects in Salesforce Apex are used to represent a single record in the Salesforce database. That means the record you fetched from the database and coming into Apex, is coming in the form of sObject. It stores all the information related to that particular record.

For Example, Account is Salesforce’s standard object, and we want to fetch a single record from the account object. The data type we use to store the fetched record is sObject.

Account myAcc = new Account ( Name='Alex Anderson', Industry='Technology' );
//Here, we creates sObject variable named myAcc that can hold data for a single Account record.

3. Collection Data Type in Salesforce Apex

In Salesforce Apex, collection data types are used to store similar information together. The collection data type can store more than one value. For example, if you want to store multiple integers together, you can use a collection.

There are three types of collection in Salesforce Apex:

1. List Collection in Salesforce

The list is a collection data type that stores information in a sequential format with an index. The list index always starts from 0. In Apex, the list size can be increased or decreased at runtime; it depends on the number of elements that you are adding to it.

  • When we execute the list, we get the output in sequential order.
  • The values can be duplicated in the list; the list doesn’t restrict the duplicate values in the apex collection.

Syntax of declaring a List collection:

List <Datatype> myList = new <Datatype>();

List<Integer>myList = new List<Integer>{1,8,6,4,6,9};   //OR

List<Integer>myList = new<Integer>(); 
myList.add (5);
myList.add (7);
myList.add (9);
system.debug( 'Collection of List is: ' +myList);

2. Set Collection in Salesforce

Sets are similar to lists, but some properties of sets differ from those of lists. The elements that we store in the set collection are stored in an unordered format. The values we store in the set should be unique because they do not return duplicate values.

Syntax of declaring a Set collection:

Set<Datatype> mySet = new <Datatype>();

Set<Integer>mySet= new Set<Integer>{4,6,3,8,7,2};   //OR

Set<Integer>mySet = new<Integer>();
mySet.add (4);
mySet.add (2);
mySet.add (8);
system.debug( 'Collection of Set is: ' +mySet);

3. Map iCollection in Salesforce

In the map collection, we not only store a single value, but also two values. Where the value is associated with a particular key, in the map, the key is always unique, and the value can be duplicated.

Let’s take a student roll number and name example. Here, the roll number acts like a key, and the name acts like a value, which means that in the class, two students’ names can be the same, but their roll numbers are unique.

Syntax of declaring a Map collection:

Map<Key_Datatype,Value_Datatype> mapList = new Map<Key_Datatype,Value_Datatype>();

Map<Integer,String> mapList = new Map<Integer,String>();
mapList.put(1,'Alex');
mapList.put(2,'Emma');
mapList.put(3,'Jhon');
mapList.put(4,'Alex');
system.debug( 'Collection of Map is: ' +mapList);

On collection in Salesforce Apex, there are several methods used in collection manipulation.

4. Enum (Enumerated) Data Types in Salesforce Apex

In Salesforce, Apex enum is very useful for developers to create their own data type to define the set of values that can be included, instead of any other primitive data type variable that cannot serve that purpose.

Below, I explained an example of an enum data type:

Here, I created the Enum class, in which I defined cloud technologies. The values we defined in the enum class, except for these values, will not be accepted at all.

public enum CloudTechnologies{

        Salesforce, AWS, Microsoft Azure, Google Cloud, Oracle Cloud

}

To use the user-defined enum class, we will create a public class. Since I have created a static method, we need to create an enum class instance variable with the class name.

Now, in this class, we can only assign values to the instance of the CloudTechnologies class that we declared in the enum class; if you try to assign another value, it will give an error.

public class EnumClass {
      public static void myMethod(){
          CloudTechnologies ct = CloudTechnologies.Salesforce;
          ct = CloudTechnologies.AWS;

          ct = 'Java';  //Error
       }
}

In this way, we can create an enum data type in Salesforce Apex.

Conclusion

I hope you have got an idea about variables and data types in Apex, and the various data types and their uses. Additionally, we will see how to use data types to develop Apex code in Salesforce. We have seen some syntax to use data types in Salesforce Apex, then basic methods, so using those methods, we can write Apex code.

In the next tutorial, I will explain the methods of the data types that we have covered in this tutorial.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.