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;
syst