Variables in Apex

What are Varibles in Apex

Variables are the building blocks of any programming language, and Apex is no exception. They allow developers to store, retrieve, and manipulate data effectively. In this blog, we’ll dive deep into variables in Apex, covering their types, scope, and usage with practical examples.


A variable is a named placeholder used to store data temporarily during the execution of code. Depending on its declaration, it can hold different types of data such as strings, numbers, or objects.


Here’s how you declare a variable in Apex:

DataType variableName = value;

  • DataType: The type of data the variable will hold (e.g., String, Integer, Boolean).
  • variableName: The name of the variable (should follow naming conventions).
  • value: An optional value to initialize the variable.

Example:

String accountName = 'SFDC Insights';

Integer accountCount = 10;

Boolean isActive = true;


Local Variables


Declared within a method or block and accessible only within that scope.
Example:

public static void displayMessage() {
    String message = 'Welcome to SFDC Insights';

    System.debug(message);

}

    Instance Variables


    Declared at the class level and belong to an instance of the class.
    Example:

    public class AccountHandler {
        public String accountName;
    }

      Static Variables


      Shared across all instances of a class and declared with the static keyword.
      Example:

      public class AccountHandler {
          public static Integer maxAccounts = 100;
      
      }

        Global Variables


        Built-in variables such as UserInfo are available throughout Salesforce.
        Example:

        System.debug('User ID: ' + UserInfo.getUserId());

        The scope defines where a variable can be accessed.

        • Local Scope: Accessible only within the block or method where declared.
        • Class Scope: Accessible throughout the class if declared as an instance variable.
        • Global Scope: Accessible across the platform (e.g., global variables or static variables).

        Example:

        public class VariableScopeExample {
        
            public static String instanceVariable = 'Class Scope';  // Class scope
        
            public static void showScope() {
        
                String localVariable = 'Local';  // Local scope
        
                System.debug(instanceVariable + ' ' + localVariable);
        
            }
        
        }

        1. Use meaningful names that reflect the purpose of the variable.
        2. Avoid hardcoding values directly; use variables instead for flexibility.
        3. Always initialize variables before using them.
        4. Use appropriate access modifiers (public, private, etc.) to restrict access.

        Example 1: Using Local and Instance Variables

        public class VariableDemo {
        
            public  String instanceVariable = 'Instance Variable';
        
            public  void displayVariables() {
        
                String localVariable = 'Local Variable';
        
                System.debug('Instance: ' + instanceVariable);
        
                System.debug('Local: ' + localVariable);
        
            }
        
        }

        Example 2: Working with Static Variables

        public class StaticDemo {
        
            public static Integer staticCount = 0;
        
            public static void incrementCount() {
        
                staticCount++;
                System.debug('Value of staticCount > ' + staticCount);
        
            }
        
        }

        Example 3: Using Global Variables

        public class GlobalVariableDemo {
        
            public void showUserInfo() {
        
                System.debug('User Id: ' + UserInfo.getUserId());
        
            }
        
        }

        Uninitialized Variables:

        Integer count; 
        count = count + 5;
        System.debug(count); // NullPointerException

        1. Variable Name Conflicts: Avoid using reserved keywords or duplicate names.
        2. Improper Scope Usage: Declaring variables in the wrong scope leads to access issues.

        Understanding variables in Apex is a crucial step in mastering Salesforce development. From local to global, each type of variable serves a unique purpose, enhancing the modularity and readability of your code. Explore more about how to integrate these concepts into real-world Salesforce solutions.

        Ready to practice? Start coding and see how variables transform your Apex classes!

        Comments

        No comments yet. Why don’t you start the discussion?

        Leave a Reply

        Your email address will not be published. Required fields are marked *