Variables in Apex programming in Salesforce

Variables in Apex programming in Salesforce

On January 9, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Variables in Apex programming in Salesforce

What is a variable?


In Apex, a variable is a named storage location that holds a value which can be changed during the execution of the program. Think of it as a container or a small box where you can store information. This information can be a number, text, a date, or even a complex piece of data like a customer record. In Apex, you define a variable by specifying its type (like Integer, String, or Date), giving it a name, and optionally setting it to a specific value. Variables are fundamental in programming as they allow you to store, modify, and retrieve data as your program runs, making it dynamic and flexible.

You can read the previous article Salesforce Apex Tutorial – Chapter 4: Data Types In Apex and previous one Salesforce Apex Tutorial – Chapter 6: Apex Strings.

Let’s explore more details about variables in apex.

The declaration of variables in Apex is quite similar to java. Following is the syntax to declare an apex variable:

type identifier = value;

Below are a few examples of apex variables.

String name =Test; // String variable declaration
Boolean boolValue = True; // Boolean variable declaration
Integer intValue= 10; // Integer variable declaration
Decimal i = 2.5; //decimal variable declaration

Following are the features of apex variables:

  • Apex variables can be defined at any point in the code block.
  • Apex variables are case insensitive.
  • Apex variables are initialized to null if no other value is assigned to the apex variable during declaration.
  • A variable defined in a method has scope within the method only.

In Salesforce, Apex is a strongly-typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce platform server, in conjunction with calls to the API. Understanding how to use variables in Apex is fundamental. Variables are used to store data that can be changed or manipulated within the program. Here’s an introduction to variables in Apex:

Types of Variables in Apex

  1. Primitive Data Types: These include Integer , Long , Double , Decimal , String , Date , Datetime , and Boolean .
  2. sObject Types: These are specific to Salesforce and represent objects (like Account , Contact , Lead , etc.).
  3. Collections: These include List , Set , and Map .
  4. Enums: These are a distinct type that consists of a fixed set of constants.

Declaring Variables

Variables in Apex must be declared with a specific data type. The syntax for declaring a variable is:

DataType variableName;

For example, to declare an integer variable:

Integer count;

Initializing Variables

Variables can be initialized (assigned a value) when they are declared, or at any point later in the program.

For example:

Integer count = 5; String greeting = ‘Hello, world!’;

Example of Variable Usage in Apex

public class VariableDemo {
public static void main(String[] args) {
// Declaring and initializing variables
Integer count = 10;
String message = 'Hello Salesforce';
    // Using variables in the code
    for(Integer i = 0; i < count; i++) {
        System.debug(message + ' ' + i);
      }
   }
}

Types of Variables in Salesforce

  • Local Variables
  • Instance Variables
  • Static Variabless
  • Global Variables
  • Constants
  • Collection Variables

Local Variables

In Salesforce Apex, local variables are variables that are declared within a method and are accessible only within that method. They are created when the method is called and exist until the method has finished executing. Local variables help in performing operations within a method and are not accessible outside of it, ensuring a level of encapsulation and preventing unintended modifications from outside the method.

Here are three coding examples demonstrating the use of local variables in Apex:

Example 1: Simple Arithmetic Operation

public class Calculator {
    public static Integer addNumbers() {
        // Declaring local variables
        Integer a = 10;
        Integer b = 20;
        
        // Adding numbers
        Integer sum = a + b;
        
        // Returning result
        return sum;
    }
}

Example 2: Looping Through a List

public class ListProcessor {
public static void processList(List numbers) {
// Declaring a local variable to hold the sum
Integer total = 0;

    // Looping through the list of numbers
    for(Integer num : numbers) {
        // Adding each number to the total
        total += num;
    }

    // Printing the total
    System.debug('Total: ' + total);
}
}

Example 3: Working with Strings

public class StringFormatter {
public static String formatString(String input) {
// Declaring a local variable to hold the formatted string
String result = input.trim();

    // Converting string to upper case
    result = result.toUpperCase();

    // Returning the formatted string
    return result;
}

}

Instance Variables

Instance variables, also known as member variables, are variables that are declared within a class but outside any method, constructor, or block. In Salesforce Apex, these variables are used to store data that is unique to each instance of the class.

Characteristics of Instance Variables in Salesforce Apex:

  1. Scope: Instance variables are accessible from any non-static method in the class.
  2. Lifetime: They exist as long as the instance of the class exists.
  3. Default Values: They are initialized to default values (e.g., null for objects, 0 for numbers) if not explicitly initialized.

Examples:

Example 1: Defining and Using an Instance Variable

public class Car {
    // Instance variable
    public String model;

    // Constructor to set the model of the car
    public Car(String m) {
        model = m;
    }

    // Method to display the model of the car
    public String getModel() {
        return model;
    }
}

// Using the class
Car myCar = new Car('Tesla Model S');
System.debug(myCar.getModel()); // Output: Tesla Model S

Example 2: Instance Variables with Different Data Types

public class Employee {
    // Instance variables
    public String name;
    public Integer age;
    public Double salary;

    // Method to set the employee's details
    public void setDetails(String n, Integer a, Double s) {
        name = n;
        age = a;
        salary = s;
    }

    // Method to display the employee's details
    public String getDetails() {
        return 'Name: ' + name + ', Age: ' + age + ', Salary: ' + salary;
    }
}

// Using the class
Employee emp = new Employee();
emp.setDetails('John Doe', 30, 90000.00);
System.debug(emp.getDetails()); // Output: Name: John Doe, Age: 30, Salary: 90000.0

Example 3: Instance Variables in Object-Oriented Context

public class Account {
// Instance variable
private Decimal balance;

// Constructor
public Account(Decimal initialBalance) {
    balance = initialBalance;
}

// Method to deposit money
public void deposit(Decimal amount) {
    balance += amount;
}

// Method to withdraw money
public Boolean withdraw(Decimal amount) {
    if (amount <= balance) {
        balance -= amount;
        return true;
    }
    return false;
}

// Method to get the current balance
public Decimal getBalance() {
    return balance;
}

}

// Using the class
Account acc = new Account(500.00);
acc.deposit(200.00);
System.debug(acc.getBalance()); // Output: 700.00
Boolean result = acc.withdraw(100.00);
System.debug(result); // Output: true
System.debug(acc.getBalance()); // Output: 600.00

Static Variables

In Salesforce Apex, the keyword static is used to define static methods and variables. Static members (methods and variables) are associated with the class itself rather than any particular instance of the class. This means that the static member is shared across all instances of the class.

Here are the key characteristics of static members in Apex:

Static Variables: They retain their value between method calls and are shared across all instances of the class. They are ideal for maintaining a state that is common to all instances.

Static Methods: They can be called without creating an instance of the class. Static methods can only directly access other static members.

Examples:

1. Static Variable:

Used to maintain a count of instances of a class or to share a common state across instances.

public class Counter {
    public static Integer count = 0; // Static variable

    public Counter() {
        count++;
    }

    public static Integer getCount() {
        return count; // Accessing the static variable
    }
}

Counter c1 = new Counter();
Counter c2 = new Counter();
System.debug(Counter.getCount()); // Output: 2

Global Variables

In Salesforce Apex, global variables are not variables in the traditional sense, but rather, they are references to context-specific information available in Visualforce pages or Apex classes. These global variables allow you to access information about the current user, organization, or the current page request, among others. They are typically used in Visualforce pages to personalize page content according to the user’s context.

Here are three examples demonstrating the use of global variables in Salesforce Apex:

Example 1: Accessing User Information

// Accessing information about the current user
UserInfo.getUserName(); // Returns the user's full name
UserInfo.getUserId(); // Returns the user's ID
UserInfo.getUserEmail(); // Returns the user's email address

This example shows how you can use the UserInfo global variable to access information about the user currently logged into the Salesforce session.

Example 2: Accessing Organization Information

// Accessing information about the organization
Organization org = [SELECT Id, Name, PrimaryContact FROM Organization LIMIT 1];
System.debug('Organization Name: ' + org.Name);
System.debug('Primary Contact: ' + org.PrimaryContact);

In this example, the Organization object is used to retrieve information about the organization, such as its name and primary contact. This isn’t a global variable per se, but it demonstrates how to access global information about the Salesforce organization.

Example 3: Using Global Variables in Visualforce Pages

// In a Visualforce Page
<apex:page>
    <p>Hello, {!$User.FirstName} {!$User.LastName}</p>
    <p>Your profile name is: {!$Profile.Name}</p>
    <p>Your session started at: {!$Api.Session_ID}</p>
</apex:page>

This Visualforce page snippet uses global variables to personalize the content. $User accesses information about the current user, $Profile accesses information about the user’s profile, and $Api.Session_ID retrieves the current session ID.

While these examples showcase how to use global-like constructs in Salesforce to access specific information about the user context, session, or organization, it’s important to note that Apex doesn’t have global variables in the same sense as languages like JavaScript or Python. Instead, Salesforce provides system classes and Visualforce global variables to access this kind of information.

Constants

Constants in Salesforce Apex are variables whose values are set at the time of declaration and cannot be changed afterward. Constants are defined using the final keyword, and it is a common practice to name constant variables in all uppercase letters to distinguish them from other variables. They are typically used to store values that remain the same throughout the execution of the program.

Here are three coding examples demonstrating the use of constants in Salesforce Apex:

Example 1: Basic Constant Declaration

public class Circle {
    // Constant for Pi
    public static final Double PI = 3.14159;
    
    // Method to calculate area of a circle
    public static Double calculateArea(Double radius) {
        return PI * radius * radius;
    }
}
Double area = Circle.calculateArea(5.0);
System.debug('Area of the circle: ' + area); // Output: Area of the circle: 78.53975

In this example, PI is a constant representing the mathematical constant π (pi). It’s used in the method calculateArea to compute the area of a circle.

Example 2: Constants in Configuration

public class AppConfig {
    // Constants for application configuration
    public static final String APP_NAME = 'SalesTracker';
    public static final Integer MAX_LOGIN_ATTEMPTS = 3;
    
    // Method to display config details
    public static String getConfigDetails() {
        return 'App Name: ' + APP_NAME + ', Max Login Attempts: ' + MAX_LOGIN_ATTEMPTS;
    }
}

String configDetails = AppConfig.getConfigDetails();
System.debug(configDetails); // Output: App Name: SalesTracker, Max Login Attempts: 3

Here, APP_NAME and MAX_LOGIN_ATTEMPTS are constants used for application configuration. Their values are set once and used throughout the application.

Example 3: Constants for Error Messages

public class ErrorMessages {
    // Constants for error messages
    public static final String ERROR_LOGIN = 'Login failed. Please try again.';
    public static final String ERROR_ACCESS_DENIED = 'Access denied. You do not have the necessary permissions.';
    
    // Method to log error message
    public static void logError(String errorType) {
        if (errorType == 'login') {
            System.debug(ERROR_LOGIN);
        } else if (errorType == 'access') {
            System.debug(ERROR_ACCESS_DENIED);
        }
    }
}

ErrorMessages.logError('login'); // Output: Login failed. Please try again.

In this example, ERROR_LOGIN and ERROR_ACCESS_DENIED are constants that store standard error messages. They are used in the logError method to log specific error messages based on the error type.

These examples illustrate how constants are used in Apex to store values that do not change throughout the execution of the program, providing a way to maintain clean, manageable, and less error-prone code.

Collection Variables

In Salesforce Apex, collection variables are special types of variables that can store multiple values. Apex provides three types of collection variables: Lists, Sets, and Maps.

  1. Lists: An ordered collection of elements that are distinguished by their indices.
  2. Sets: An unordered collection of elements that do not contain any duplicates.
  3. Maps: A collection of key-value pairs where each unique key maps to a single value.

Example 1: List

Lists are ordered collections and can contain duplicate elements.

List<String> fruits = new List<String>(); // Declare a new list of Strings
fruits.add('Apple'); // Add elements to the list
fruits.add('Banana');
fruits.add('Cherry');
System.debug(fruits); // Output: (Apple, Banana, Cherry)

// Access elements by index
String firstFruit = fruits[0]; // Apple
System.debug(firstFruit);

// Get the size of the list
Integer size = fruits.size(); // 3
System.debug(size);

Example 2: Set

Sets are unordered collections of unique elements.


<p>Set numbers = new Set(); // Declare a new set of Integersnumbers.add(1); // Add elements to the setnumbers.add(2);numbers.add(3);numbers.add(1); // Duplicate, will not be added to the setSystem.debug(numbers); // Output: {1, 2, 3}</p>



<p>// Check if the set contains a specific elementBoolean containsTwo = numbers.contains(2); // trueSystem.debug(containsTwo);</p>



<p>// Get the size of the setInteger setSize = numbers.size(); // 3System.debug(setSize);</p>

Example 3: Map

Maps are collections of key-value pairs. Each unique key maps to a single value.

Map<String, Integer> productQuantities = new Map<String, Integer>(); // Declare a new map
productQuantities.put('Apples', 5); // Add key-value pairs to the map
productQuantities.put('Oranges', 8);
productQuantities.put('Bananas', 12);
System.debug(productQuantities); // Output: {Apples=5, Oranges=8, Bananas=12}

// Access value by key
Integer appleQuantity = productQuantities.get('Apples'); // 5
System.debug(appleQuantity);

// Check if the map contains a specific key
Boolean hasOranges = productQuantities.containsKey('Oranges'); // true
System.debug(hasOranges);

// Get the size of the map
Integer mapSize = productQuantities.size(); // 3
System.debug(mapSize);

Frequently Asked Interview Questions

What is the difference between local variables and instance variables in Apex, and how are they scoped?

The distinction between local variables and instance variables in Apex is crucial, primarily focusing on their scope, lifetime, and use cases.

Local Variables: Local variables are declared and used within a method. Their scope is strictly confined to the method in which they are declared, meaning they are not accessible outside that method. The lifetime of a local variable is limited to the duration of the method’s execution. As soon as the method completes, the local variable is out of scope, and its memory is reclaimed by the garbage collector. Before use, local variables must be initialized; otherwise, Apex will throw a compilation error. These variables are typically used for temporary storage and intermediate calculations within a method.

Here’s a simple example demonstrating the use of a local variable:

public class Calculator {
    public Integer sum(Integer a, Integer b) {
        Integer result = a + b; // 'result' is a local variable
        return result;
    }
}

Calculator calc = new Calculator();
System.debug(calc.sum(5, 10)); // Output: 15

In this example, result is a local variable within the sum method. It’s used to store the result of adding two numbers and is not accessible outside the sum method.

Instance Variables (Member Variables): Instance variables, on the other hand, are declared at the class level, outside of any specific method. They represent the state of an instance of the class and are accessible by all methods in the class. If their access modifier allows, they can also be accessed by methods of other classes. The lifetime of an instance variable is tied to the object itself; the variable exists as long as the object exists. Unlike local variables, instance variables do not require explicit initialization; they are automatically initialized to a default value (null for objects, false for booleans, 0 for numeric types). These variables are ideal for storing the properties or state of an object that needs to be shared across multiple methods.

Below is an example that uses an instance variable:

public class BankAccount {
private Integer balance; //

How can you define and use constants in Apex, and what are their typical use cases?

Constants in Salesforce Apex are variables that are declared with the final keyword and are intended to remain unchanged throughout the program. Once a constant is assigned a value, it cannot be altered. Constants are useful when you need a fixed, unchangeable value to be accessible across multiple parts of your application, ensuring that the value is consistent and prevents accidental changes.

Characteristics of Constants:

  1. Immutable: Once initialized, constants cannot be reassigned to different values.
  2. Class Level: Constants are often declared at the class level, making them accessible throughout the class and maintaining a single, unchangeable value.
  3. Static: Constants are usually declared as static , ensuring there is only one instance of the variable regardless of how many objects of the class are created.
  4. Naming Convention: By convention, constant names are in uppercase letters, with words separated by underscores, to make them easily identifiable as constants.

Example 1: Basic Constant

public class MathConstants {
    // Declaring a constant
    public static final Double PI = 3.14159;

    public static Double calculateCircleArea(Double radius) {
        return PI * radius * radius;
    }
}

System.debug(MathConstants.calculateCircleArea(5)); // Output: 78.53975

What are collection variables in Apex, and how do they differ from single-value variables?

Certainly, the third question pertains to collection variables in Salesforce Apex, which are a crucial part of the language, allowing developers to store and manage multiple values in a structured manner. In Apex, there are three main types of collection variables: Lists, Sets, and Maps. Each of these types serves different purposes and has unique characteristics.

1. Lists:

A List is an ordered collection of elements that are distinguished by their indices. Lists can contain duplicate elements and are resizable.

Usage Example:

List<String> names = new List<String>(); // Declaring a list
names.add('John'); // Adding elements
names.add('Jane');
names.add('John'); // Lists allow duplicates

System.debug(names); // Output: ['John', 'Jane', 'John']
System.debug(names[0]); // Accessing element by index, Output: 'John'

2. Sets:

A Set is a collection that contains no duplicate elements and has no defined order for its elements.

Usage Example:

Set uniqueNames = new Set(); // Declaring a set
uniqueNames.add('John'); // Adding elements
uniqueNames.add('Jane');
uniqueNames.add('John'); // Adding a duplicate value, which will be ignored

System.debug(uniqueNames); // Output might be in any order, e.g., {'Jane', 'John'}

3. Maps:

A Map is a collection of key-value pairs where each unique key maps to a single value. Keys are unique, and each key can map to only one value.

Usage Example:

Map<String, Integer> ageMap = new Map<String, Integer>(); // Declaring a map
ageMap.put('John', 25); // Adding key-value pairs
ageMap.put('Jane', 30);
System.debug(ageMap); // Output: {'John'=>25, 'Jane'=>30}
System.debug(ageMap.get('John')); // Accessing value by key, Output: 25

In summary, collection variables in Salesforce Apex are powerful tools for managing groups of objects. Lists are ideal for ordered collections that may contain duplicates, Sets ensure that there are no duplicates and do not maintain any order, and Maps are perfect when you need to associate unique keys with specific values. These collections are fundamental to handling multiple data objects in Salesforce Apex, making data manipulation and retrieval efficient and straightforward.

How do global variables in Apex differ from class-level variables, and what are their typical use cases?

Global Variables in Apex: Global variables are special variables provided by Salesforce that are available in specific contexts. They are not declared by the developers but are provided by the system. These variables are used to access context-specific information, such as information about the current user, the current organization, or the current record in context. Global variables are recognized by their syntax, which usually starts with a dollar sign ( $ ).

Example Use Cases:

  • Accessing the current user’s information (e.g., $User ).
  • Accessing organization-level information (e.g., $Organization ).
  • Accessing custom labels (e.g., $Label ).

Here’s an example of how you might use a global variable in a Visualforce page to display the current user’s name:

<apex:page>
<h1>Welcome, {!$User.FirstName} {!$User.LastName}!</h1>
</apex:page>

Class-level Variables in Apex: Class-level variables, on the other hand, are variables that you declare at the class level, outside of any methods. These can be instance variables (member variables) or class variables (static variables). Instance variables are specific to each instance of the class, while static variables are shared across all instances of the class.

Example Use Cases:

  • Instance Variable: Storing object-specific data, like the account number of a bank account object.
  • Static Variable: Storing class-wide information, like the total number of instances of the class that have been created.

Here’s an example of how you might use instance and static variables in Apex:

public class BankAccount {
    // Instance variable
    public String accountNumber;
    
    // Static variable
    public static Integer totalAccounts = 0;

    // Constructor
    public BankAccount(String accountNumber) {
        this.accountNumber = accountNumber;
        BankAccount.totalAccounts++;
    }

    // Method to display account information
    public String displayInfo() {
        return 'Account Number: ' + accountNumber;
    }
    
    // Static method to get total accounts
    public static Integer getTotalAccounts() {
        return totalAccounts;
    }
}

BankAccount account1 = new BankAccount('123456');
System.debug(account1.displayInfo()); // Output: Account Number: 123456
System.debug(BankAccount.getTotalAccounts()); // Output: 1

In this example, accountNumber is an instance variable, unique for each BankAccount object, and totalAccounts is a static variable, shared across all instances of BankAccount . Each time a new BankAccount is created, the constructor increments the totalAccounts .

In summary, global variables in Apex provide access to context-specific information and are system-defined, while class-level variables (instance and static) are developer-defined and are used to store object-specific or class-wide data respectively. Global variables are mostly used in templates and expressions (like Visualforce or Lightning), whereas class-level variables are used within Apex classes to maintain states and behaviors.

Can you provide examples of when and how to use different types of collection variables (List, Set, Map) in Apex?

Collections in Apex are powerful data structures that can store multiple elements and are crucial for handling groups of objects.

List

A List is an ordered collection of elements that can contain duplicates. Lists are commonly used when the order of elements matters or when you might need to access elements by their index.

Example:

List<String> names = new List<String>();
names.add('John');
names.add('Jane');
names.add('John'); // Lists allow duplicate elements

// Accessing elements by index
String firstName = names[0]; // John
System.debug('First name in the list: ' + firstName);

// Iterating through the list
for(String name : names) {
    System.debug(name);
}

Set

A Set is a collection that contains no duplicate elements and does not maintain the order of its elements. Sets are useful when you want to ensure that a collection contains unique elements and when the order of insertion is not important.

Example:

Set<String> uniqueNames = new Set<String>();
uniqueNames.add('John');
uniqueNames.add('Jane');
uniqueNames.add('John'); // This 'John' is ignored because sets do not allow duplicates

// Checking if a set contains an element
Boolean hasJohn = uniqueNames.contains('John');
System.debug('Does the set contain John? ' + hasJohn);

// Iterating through the set
for(String name : uniqueNames) {
    System.debug(name);
}

Map

A Map is a collection of key-value pairs where each key maps to a single value. Keys are unique in the map, and each key can map to at most one value. Maps are beneficial when you need fast access to elements based on a key.

Example:

Map<Id, Account> accountMap = new Map<Id, Account>();
Account acc1 = new Account(Name='Acme Corporation');
Account acc2 = new Account(Name='Global Services');

// Adding accounts to the map with their IDs as keys
accountMap.put(acc1.Id, acc1);
accountMap.put(acc2.Id, acc2);

// Accessing an element by key
Account retrievedAcc = accountMap.get(acc1.Id);
System.debug('Retrieved Account: ' + retrievedAcc.Name);

// Iterating through the map
for(Id accId : accountMap.keySet()) {
    System.debug('Account Name: ' + accountMap.get(accId).Name);
}

In summary, List , Set , and Map are versatile collection types in Apex that serve different purposes. Lists are ordered and allow duplicates, Sets ensure uniqueness of elements and do not maintain order, and Maps provide a way to store and access key-value pairs efficiently. The choice of collection type depends on the specific requirements of your use case, such as the need for ordering, uniqueness, or fast access by key.

Each collection type in Apex serves a unique purpose. Lists are great for ordered collections and allow duplicates. Sets ensure uniqueness and offer fast existence checks. Maps provide a powerful way to associate unique keys with specific values and allow fast retrieval by key. The choice of which collection type to use depends on the specific requirements of your application, such as the need for ordering, the requirement of unique elements, or the necessity for fast lookups by key.

Comments are closed.