Introduction to Apex programming

The goal for the chapter is to establish a robust foundation of the basics of Apex, focusing on syntax, data types, and foundational object-oriented programming (OOP) principles. Mastering apex is the key to becoming proficient in Apex programming language that is in turn pivotal to becoming a good Salesforce Developer.

With this chapter we will break down the essential components of Apex into smaller easily comprehendible chunks. These foundational blocks will help you throughout your Salesforce Development career. Let’s dive in!

Introduction to Apex in Salesforce for developers

Apex is Salesforce’s proprietary programming language, closely resembling Java in its syntax and structure. It’s designed specifically for building robust and scalable applications within the Salesforce platform. Apex operates on the Force.com platform, which provides developers with a controlled environment for creating custom business logic that is integrated tightly with the Salesforce data model.

What is Apex programming used for in Salesforce?

Apex is Salesforce’s proprietary programming language. It is similar to Java in its syntax and structure designed for any custom development within the Salesforce platform. Built on the Salesforce Platform (formerly known as Force.com), Apex integrates closely with the platform’s data model, security, and user interfaces offering seamless interaction with Salesforce objects and records. It helps build and develop scalable applications and manipulate data and more on the Salesforce platform’s multi-tenant architecture.

Common use cases of Apex code in Salesforce:

  • Custom Business Logic and Automation: Automating business processes using custom Triggers on database operations. Scheduling tasks for specific times using Apex Scheduler.
  • Data Manipulation: Perform DML operations like create, update and delete on Salesforce records.
  • Third-Party Integrations: Integrating with external systems via API calls allowing Salesforce to communicate with other systems.

How to get started with Apex for Salesforce development

Salesforce Admin job roles are good but to build a long term career in Salesforce and to boost your employability on paper as well, you must sharpen your development skills in Apex. Apex knowledge gives developers granular control over business logic and empowers them to deliver more value to businesses using Salesforce.

Some Terms to get familiar with:

  1. Strongly and Weakly Typed Programming Language
    A programming language is said to be strongly typed when there are restrictions imposed by type system and it demands the specification of data types. While it is loosely or weakly typed, when the compiler does not enforce a typing discipline, or has some workaround it. The definitions have been subject to long discussions.
  2.  Statically and Dynamic Typed Programming Language
    Statically typed languages is where the type is bound to the variable and are checked at compile time. Examples: C, C++, Java. While Dynamically typed programming languages is where the type is bound to the value and are checked at run-time. Example: JavaScript.

Understanding Salesforce Apex syntax and data types

Apex syntax is very similar to that of Java as mentioned earlier in this post hereby any background in Java would make this resemble more.

Apex Syntax Overview

In this example, we declare a simple Apex class (Intro) and a method (greeting) that prints “Hello World!” in the debug log. Apex is case sensitive.

public class Intro {
public static void greeting() {
System.debug('Hello World!');
}
}

Apex being a strongly typed language requires us to declare the variables with specific data types . Lets look at some primitive data types used in Apex:

What are primitive data types in Apex?

  • Boolean: Can be assigned with truefalse, or null
  • Integer: A 32-bit whole numbers, both positive and negative
  • Decimal: A number with a decimal point.
  • Long: A 64-bit number that doesn’t include a decimal point
  • Double: A 64-bit floating-point number (decimals)
  • Date:  A particular day
  • Time: A particular time
  • Datetime: A particular day and time
  • Blob: A collection of binary data
  • Id: 18-character record identifier. 
  • String: Any set of characters under single quotes
  • Object: All Apex data types inherit from Object.

Example:

Object obj = 25;
// Cast the object to an integer.
Integer age =(Integer)obj;


Long worldPopulation = 8000000000L;
Boolean isEmployed = true;
String name = 'Marie';
Date tDay = Date.newInstance(2020,9,30);
Time dTime = Time.newInstance(3, 35, 0 ,0);
DateTime dt = DateTime.newInstance(2020,9,30,3, 35, 0);

How to use variables and expressions in Apex

Variables are containers that help store data values.

Declaring Variables

To declare a variable in Apex, we specify the data type before the variable name as in the example below.

String msg = 'Welcome to SalesforceHandle!';

Expressions in Apex

Expressions are combinations of variables, operators and method invocations that help process data with a required logic to produce output values. It is valid unit of code that evaluates to a value. For example:

Integer result = count + 10;

Operators in Apex

Operators are symbols that help perform logical operations on variables or values to produce results. Apex supports various operators using which we can effectively write dynamic and powerful Apex code. Let understand some commonly used operators in Apex.

Assignment operator (=)

Integer x = 5;

Addition operator (+)

x = x + 5;

Subtraction operator (-)

x = x - 5;

Multiplication operator (*)

x = x * 5;

Division operator (/)

x = x/5;

Increment operator (++)

x++; 

//same as x+1

Decrement operator (–)

x--; 
//same as x-1

Addition assignment operator (+=)

x += 5; 
//same as x = x+5;

Subtraction assignment operator (-=)

x -= 5; 
// same as x = x-5;

Multiplication assignment operator (*=)

x*= 5; 
// same as x = x*5;

Division assignment operator (/=)

x /= 5; 
// same as x = x/5;

AND assignment operator (&&)

Boolean a = true;
Boolean b = false;
Boolean result;

//AND Operator
result = a && b;

// both first and second is true, then final is true, else it is false
Boolean isAdult = (age > 18) && (age < 60); // Checks if age is between 18 and 60

OR operator (||)

Boolean a = true;
Boolean b = false;
Boolean result;

//AND Operator
result = a || b;

// if either of the first and second is true, then final is true, else it is false

Equality operator (==)

Boolean result = (5 == '5'); //TRUE
// if both expressions have the same value, then true, else false

Exact equality operator (===)

Boolean result = (5 === 5); //FALSE
// if both expressions have the same value and type, then true, else false

Less than operator (<)

Boolean result = (5 < 6);

Greater than operator (>)

result = (5 > 6);

Less than or Equal to operator (<=)

result = (5 <= 6);
result = (6 <= 6);
9
//both are true

Greater than or equal to operator (>=)

result = (5 >= 6); //false
result = (6 >= 6); //true

NOT operator(!)

boolean a = true;
a=!a;
//  value changes from true to false

Inequality operator (!=)

result = (5 != 6); //true
result = (6 != 6); //false

Ternary operator (? 🙂
This operator acts as a short-hand for if-then-else

String greeting = '';
Integer hour = 10;
// if hour is less than 12, then greeting should be good morning
// else greeting should be good afternoon
greeting = (hour < 12) ? 'Good Morning' : 'Good Afternoon';

Above are the majorly used operators, you can refer here for more.

Working with lists, sets, and maps in Salesforce Apex

Apex collections:

Collections in Apex help developers to store and manipulate large amounts of data efficiently. There are three main types of collections in Apex: Lists, Sets, and Maps. They allow us to manage multiple records in one variable. There are mainly three types of collections in Apex: Lists, Sets, and Maps.

Lists in Apex:

A List is an ordered collection of elements that can may contain duplicates. We can add, remove, and retrieve elements in a List using their indices. Lists can be useful when the order of elements is of importance.

Example:

List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
System.debug(fruits[0]);  // Outputs: Apple

Sets in Apex:

A Set is an unordered collection of unique elements that do not allow duplicate values.

Example:

Set<Integer> numbers = new Set<Integer>{1, 2, 3, 3};
System.debug(numbers);  // Outputs: {1, 2, 3}

Sets are ideal to use when we want to ensure uniqueness of the collection.

Maps in Apex:

A Map is a collection of key-value pairs where each key has to be unique, though the values can be duplicates. Maps are particularly useful to manipulate data associated with an identifier such as IDs of the concerned data records, offering easier lookups based on keys.

Example:

Map<String, Integer> fruitQuantities = new Map<String, Integer>{'Apple' => 10, 'Banana' => 20};
fruitQuantities.put('Cherry', 30);
System.debug(fruitQuantities.get('Apple')); 

Apex enums and their Usage Examples in Apex

Enums in Apex are special data types that allow developers to define a set of named constants that represent fixed values. They are useful in cases where a variable needs to represent a fixed set of options. Using enums ensures that only predefined values can be assigned to a variable, reducing the risk of errors. These are useful when you want to limit the values a variable can take.

Example:

public enum IndianSeason { WINTER, SPRING, SUMMER, FALL, RAINY }
IndianSeason currentSeason = IndianSeason.RAINY;
System.debug('The current season here in India is  ' + currentSeason);

In this example, we have defined an enum called IndianSeason with there different possibilities. By using enums, we can ensure that the currentSeason variable will only have one of these predefined values. They are particularly useful when working with data like status codes, categories, or types that we would want to ensure to have a fixed number of possible values.

Conclusion

Mastering Apex language fundamentals is essential for becoming a successful developer in the Salesforce ecosystem. From learning the Apex syntax and working with primitive data types, collections like Lists, Sets, and Maps, to using enums, these foundational elements are key to advancing toward more complex topics like Apex triggers, asynchronous processing, and Salesforce integrations.

In the next chapter, we’ll dive into OOP concepts in Apex, exploring Inheritance and Polymorphism in the context of Apex programming. If you have any questions along the way, don’t hesitate to ask—this learning journey is designed to be challenging yet highly rewarding. Keep moving forward!

1 thought on “Introduction to Apex programming”

Leave a Reply

error: Content is protected !!