Hello coding crew! Today, I want to talk to you about how variables, primitive data types, and their methods are used in Salesforce Apex language. Don’t worry if you haven’t read about this topic before, or if you’re not sure what variables are – I’ve got your back.
What are Variables in Salesforce?
Variables are a key concept that you will use day-to-day in your coding, and they are also very simple. Think of variables like cells in an Excel spreadsheet.
Cell in Excel Spreadsheet | Salesforce Variable |
---|---|
A cell in Excel can hold a value, such as a number or a piece of text. | A variable in Salesforce is a placeholder that can hold data of a specific data type, such as a number, string, date, and so on. |
To refer to a cell, we use its column and row, such as A2 or B6. | In Salesforce, we give a variable a name so that we can reference and use its value in our code. |
In comparison to Excel spreadsheets, variables in Salesforce are much more powerful. In addition to being able to store simple single values, they can also handle complex data structures like arrays.
- In this blog, we will focus on simple single values and discuss the different types, as well as the available out-of-the-box methods that you can use with them.
- If you’re interested in learning about complex structured data types in Salesforce, check out my blog post “Beginner’s Guide to Salesforce Apex: An Introduction to Collections – Lists, Sets, and Maps“. I cover all the details on Salesforce collections and their unique capabilities. If you’re just looking for a quick overview, my previous blog post “Essential Salesforce Developer Vocabulary for Beginners” has a brief description of Maps, Lists, and Sets.
Variable Declaration, Initialization & Usage
Two words that you will frequently hear when working with Salesforce variables are ‘declaration‘ and ‘initialization‘,
Variable Declaration
It means specifying the variable type and its name. Below is an example that explains how to define (declare) a variable:
- You will notice that we didn’t give the variable any initial values
- The values of the variables in the example below are NULL (empty).
//This is how we would declare a variable
//Variable_Data_Type variableName;
//1. Variable_Data_Type: this would be the type of the variable you need (simple or complex)
//2. variableName : this would be the variable name that you will use to access it in the code
//Examples:
Integer studentAge; //Variable of type Integer and name studentName
Decimal averageMarks; //Variable of type Decinmal and name averageMarks
Variable Initialization
It means specifying the initial value of the variable. Below is an example that explains how to initialize a variable (i.e., declare the variable and set a default value):
Integer studentAge = 18; //Variable of type Integer,name studentName & default value 18
Decimal averageMarks = 22.3;//Variable of type Decinmal, name averageMarks & default value 22.3
Variable Usage
After a variable is declared or initialized:
- We can update its value in the code at any time.
- The new value must be of the same data type that was used to declare the variable.
Integer studentAge=19;
.....
.....
studentAge = 20; //Change the studentAge value from 19 to 20
//Variable declaration only without initialization
Decimal averageMarks;
....
.....
averageMarks = 22.7; //before that line averageMarks was NULL, set its value to 22.7
What are the Primitive Data Types?
Each variable will have a specific data type. Salesforce primitive data types represent basic, single values, such as numbers, strings, booleans, dates, and so on.
It is important to know what are the different salesforce primitive data types as they are commonly used.
Number Types
Integer, Long, Double and Decimal data types are used to store number values, either whole or decimal. For example: age, salary, average, total, and so on.
Integer and Long Data Types
Both Integer and Long data types are used to store whole numbers (no decimal points allowed).
Integer Data Type | Long Data Type |
---|---|
Smaller Range: -2,147,483,648 to 2,147,483,647 | Larger Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
Integer variables use less memory | Long Variable can store larger numbers |
Examples of Declaring an Integer Variable and a Long Variable:
//declare an Integer variable with name intValue and initialize it with a whole number 10
Integer intValue = 10;
//declare a Long variable with name longValue and initialize it with a whole number 1234567890
//notice the "L" after the whole number, this to indicate that the number is treated as long
Long longValue = 9223372036854775807L;
Be careful when assigning a really big number to a Long variable in your code without using the ‘L’ character. If you don’t use the ‘L’ character, you might see an error message that says ‘Illegal Integer’. So, make sure to always add that ‘L’ character to the end of your value when you’re working with Long variables.
//9223372036854775807 is exceeding the Integer range
//We didn't include the L character at the end of the number
Long longValue = 9223372036854775807;
Double and Decimal Data Types
Both Double and Decimal data types are used to store decimal numbers.
Double Data Type | Decimal Data Type |
---|---|
It is like a ruler that measures length up to 15 decimal places | It is like a more precise ruler that measures length up to 18 decimal places. |
It takes up less memory | It takes more memory |
It is faster to compute | It takes longer to compute |
It is a good choice if you’re working with large amounts of data or need to perform calculations quickly. | It is a good choice if you need high accuracy or if you are working with financial data where even small errors can be a big deal. |
The example below will demonstrate how both data types behave differently when assigned to a value with 17 decimal points, such as 3.14159265358979396.
//define a decimal variable and print its value
//the 3.14159265358979396 has 17 decimal points
Decimal decimalValue = 3.14159265358979396;
System.debug('The Decimal Value of 3.14159265358979396 is: '+decimalValue);
//define a double variable and print its value
//the 3.14159265358979396 has 17 decimal points
Double doubleValue = 3.14159265358979396;
System.debug('The Double Value of 3.14159265358979396 is: '+doubleValue);
- The decimal data type printed the number as it is, without rounding it.
- The double data type rounded the number to the closest approximation that can be presented using 15 decimal places.
Text Type (String)
String is a data type that represents a sequence of characters, such as a word, phrase, or sentence. You can include numbers in your string too.
- String values are enclosed in single quotes (”), like this:
String welcomeText = 'Hello, coding crew to my blog number 2!';
- You can use the concatenation operator ‘+’ to combine multiple strings into one single variable
String firstName = 'Sally';
String lastName = 'Elghoul';
String welcomeNote = 'Welcome to my blog : '+ firstName + ' ' + lastName;
System.debug('Welcome Note Value: ' + welcomeNote);
Boolean Type (Boolean)
Boolean data type is a data type that has only two possible values: true or false.
Booleans are commonly used in programming to make decisions. In other words, they are often used in conditional statements to determine what actions should be taken. We will cover these conditional statements in detail in a future blog post, so stay tuned!
//compare if 3 is bigger then 2
//and return true or false in isThreeBigger
Boolean isThreeBigger = (3>2);
System.debug('isThreeBigger Value : '+isThreeBigger);
//check that firstName is equal to lastName
//and return true or false in isEqualValue
String firstName ='Sally';
String lastName ='ElGhoul';
Boolean isEqualValue = (firstName==lastName);
System.debug('isEqualValue value: '+isEqualValue);
Date Types
Date, Time, DateTime data types are used to represent date-related values, either as a date, time, or date/time.
Date
Date data type represents a date without a time component. It can be used to represent dates such as birthdays, deadlines, or other data that includes only a date and we don’t care about the time.
//Declare a variable of type Date, give it name todayDate
//Initialize the date variable with today's date..
//Date.today() is one of the methods available to use with the Date data types
Date todayDate = Date.today();
System.debug('Today date is: ' + todayDate);
Time
Time data type represents a specific time of day without a date component. It would be useful when calculating the duration of an event like a meeting.
//Declare a variable of type Time, give it name customTime
//Initialize the customTime using newInstance
//newInstance is a method available for the Time class
//newInstance parameters (Integer hour, Integer minutes, Integer seconds, Integer milliseconds)
Time customTime = Time.newInstance(9, 30, 0, 0);
System.debug('The appointment time is: ' + customTime);
DateTime
DateTime data type represents a date and time value.
- DateTime data type can be used to represent events, transactions, meeting start date/time, or other data that includes both a date and time component.
- It’s important to remember that all DateTime values are stored in the UTC (Coordinated Universal Time) time zone.
- This means that if we create a new DateTime value in Apex, it will be automatically converted to UTC time and stored in the database.
- The code sample below is an example that DateTime will be printed on the screen in UTC format by default and I had to use the method format() to display it in my timezone.
//Declare a variable of type DateTime, give it name currentDateTime
//Initialize the date variable with the current date time value
//DateTime.now() is one of the methods available to use with the DateTime data types
DateTime currentDateTime = DateTime.now();
//this debug statement will print the date time in UTC format
System.debug('The current date and time UTC: ' + currentDateTime);
//this debug statement will display the time in my current time zone
//using format() Converts the date to the local time zone
System.debug('The current date and time Est: '+currentDateTime.format());
ID Type (ID)
ID data type is used to represent the unique identifier of a record in the Salesforce database which we usually refer to as the record Id.
The record Id is generated for you when you create a record for any type and you can’t change its value.
//Declare a variable for Account data type (We will cover that in later blog)
//Set the Account Name field
Account accountCodeWithSally = new Account(Name='Code With Sally');
//Insert the account
insert accountCodeWithSally;
//Declare a variable of data type ID, and give it a name codeWithSallyID
//Initialize the ID variable codeWithSallyID with the account record ID we just created
ID codeWithSallyID = accountCodeWithSally.Id;
//Print the ID variable
System.debug('The ID of Code With Sally account is: ' + codeWithSallyID);
Primitive Data Type Methods
In Salesforce, each primitive data type (such as Integer, Double, String, DateTime, etc.) is like a special “class” that comes with its own set of built-in methods that can be used to do different things with the data. These methods are like special tools that allow you to manipulate or calculate the data in various ways.
I’m excited to share with you a brief sample of some of these methods. It’s important to note that there are many more methods available for each data type that can be useful for specific programming needs. Check out the resources below to learn more!
Data Type | Method & Usage | Sample |
---|---|---|
Integer | valueOf(StringValue) Returns an Integer that contains the value of the specified String passed. | Integer intValue = Integer.valueOf(‘567’); |
Decimal | intValue() Returns the integer value of the decimal | Decimal decimalValue = 3.456; System.debug(‘Value: ‘ + decimalValue.intValue()); Output : 3 |
Decimal | round() Returns a long value. The value returned will be a rounded number to zero decimal places. The rounding mode is ‘half-even’ which means any number will be rounded to the closes nearest neighbour and if the number has .5, the number will be rounded to the closest even neighbour | Decimal decimalValue1 = 8.5; System.debug(‘Value: ‘ + decimalValue1.round()); Output : 8 (closest even) Decimal decimalValue2 = 3.5; System.debug(‘Value: ‘ + decimalValue2.round()); Output : 4 (closest even) Decimal decimalValue3 = 8.7; System.debug(‘Value: ‘ + decimalValue3.round()); Output : 9 (closest) |
Date | addDays(NoDays) addMonths(NoMonth) addYears(noYears) These methods return a Date value and their purpose is to add ‘X’ number of days, ‘X’ number of months, or ‘X’ number of years to a specific date variable. | Date todayDate = Date.Today(); Date tomorrowDate = todayDate.addDays(1); System.debug(‘Tomorrow : ‘+tomorrowDate); If Today was 12 April, 2023 Output : ‘Tomorrow : 2023-04-13 00:00:00’ |
String | toLowerCase() toUpperCase() Returns a String value with all characters lower case or upper case | String helloText = ‘Hello Coding Crew!’; System.debug(‘Lower:’+helloText.toLowerCase()); Output: ‘Lower:hello coding crew!’ System.debug(‘Capital:’+helloText.toUpperCase()); Output: ‘Capital:HELLO CODING CREW!’ |
String | trim() Returns a copy of the string without any leading or trailing white space characters. | String helloText = ‘ Hello Coding Crew! ‘; System.debug(‘Text:’+helloText.trim()); Output: ‘Text:Hello Coding Crew!’ |
String | contains(substring) Returns true if the String calling Contains method has the substring parameter. | String helloText = ‘Hello Coding Crew!’; System.debug(‘Value:’+helloText.contains(‘Crew’)); Output : ‘Value:true’ |
String | removeEnd(substring) removeStart(substring) The ‘removeEnd’ method removes the specified substring value from the end of a String, while the ‘removeStart’ method removes it from the beginning of a String. | String helloText = ‘Test Hello Coding Crew! Test’; System.debug(‘Start:’+helloText.removeStart(‘Test’)); Output : ‘Start: Hello Coding Crew! Test’ System.debug(‘End:’+helloText.removeEnd(‘Test’)); Output : ‘End:Test Hello Coding Crew!’ |
Conclusion
In this post, we’ve explored the basics of primitive data types in Salesforce Apex. We started by defining what a variable is and how it acts as a placeholder for a certain type of data, similar to a cell in an Excel spreadsheet.
We then categorized and discussed the different types of primitive data types in Salesforce Apex, including Integer, Long, Decimal, Double, Boolean, Date, Time and DateTime.
Finally, we touched on some sample of methods that can be used as “addDays(NoDays)”,”round()”. These methods can help us manipulate and work with the data stored in our variables.
By understanding the different primitive data types available in Salesforce Apex and how to use them effectively, we can create more efficient and accurate code that performs the calculations and operations we need. Choosing the right data type and using the appropriate methods can help you achieve your goals and succeed in your projects.
Well written! This is my go-to page to review data types. Whenever I forget something or get confused with Apex vs. Java vs. JavaScript data types, I come back to this page.
On the recent cert day for PD1, there was a slide that covered primitive data types. One data type that stood out is: Blob! I didn’t know Blob is a primitive data type or if it’s new. I first thought it’s a data type for blob emoji, but learned it’s Binary Large Object. I don’t know if it’s necessary to learn that for PD1. This was never covered in any Trailhead badge. Do you have any thought about Blob?