0% found this document useful (0 votes)
18 views12 pages

Apex Variables Declaration 1737142598

The document provides an overview of variables in Apex programming within Salesforce, explaining their definition, types, and usage. It covers various variable types including primitive data types, sObject types, collections, and constants, along with examples of local, instance, static, and global variables. The document emphasizes the importance of variables in storing and manipulating data during program execution.

Uploaded by

raghu I
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views12 pages

Apex Variables Declaration 1737142598

The document provides an overview of variables in Apex programming within Salesforce, explaining their definition, types, and usage. It covers various variable types including primitive data types, sObject types, collections, and constants, along with examples of local, instance, static, and global variables. The document emphasizes the importance of variables in storing and manipulating data during program execution.

Uploaded by

raghu I
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Name- Shubham Patil

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.

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 Variables
●​ 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);

You might also like