Variable in Apex

Black BUCBlack BUC
4 min read

๐Ÿ” Why Do We Need a Variable in Apex?

In Salesforce Apex, a variable acts as a container used to store a value during the execution of a program. These stored values can be reused, updated, or passed to methods throughout an Apex transaction.


๐Ÿ“Œ What Is a Variable?

  • A variable holds data temporarily in memory.

  • The name of a variable is called an identifier.

  • Identifiers:

    • Must start with a letter (Aโ€“Z or aโ€“z)

    • Can include numbers (0โ€“9) after the first character

    • No specific length limit


๐Ÿง  Primitive Data Types in Apex

Apex supports several built-in primitive data types:


๐Ÿงฎ a. Numeric Data Types

โœ… Integer

  • Whole numbers only, no decimals.

  • Range: โ€“2,147,483,647 to 2,147,483,647

Integer count = 100;
System.debug(count);

โœ… Long

  • Like Integer, but supports larger values.

  • Suffix L is mandatory

Long bigNum = 9999999999L;
System.debug(bigNum);

โœ… Decimal

  • Numbers with decimal points.

  • Precise: up to 16 digits before and 34 digits after the decimal

Decimal price = 1234.5678;
System.debug(price);

โœ… Double

  • Similar to Decimal, but less precise.

  • Suffix d can be used (optional)

Double weight = 75.35d;
System.debug(weight);

๐Ÿ”ค b. Text Type

โœ… String

  • Sequence of characters in single quotes.

  • No length limit.

String name = 'Apex Developer';
System.debug(name);

๐Ÿ“† c. Date & Time Types

โœ… Date

  • Represents only a date, not time.

  • Can use Date.newInstance() or System.today()

Date dob = Date.newInstance(1995, 5, 14);
System.debug(dob);

โœ… DateTime

  • Represents both date and time.
DateTime dt = DateTime.newInstance(2022, 9, 2, 12, 5, 0);
System.debug(dt);

โœ… Time

  • Represents time only (hours, minutes, seconds, milliseconds).
Time t = Time.newInstance(10, 30, 0, 0);
System.debug(t);

๐ŸŽฏ d. Other Data Types

โœ… Id

  • Stores record Ids from Salesforce.

  • Automatically converts 15-digit Ids to 18-digit at runtime.

Id recordId = '0015g00000p1F2z';
System.debug(recordId);

โœ… Boolean

  • Stores true, false, or null.
Boolean isActive = true;
System.debug(isActive);

โœ… Blob (Binary Large Object)

  • Used to store binary data (e.g., files, attachments).

  • Commonly used with encoding/decoding logic.

Blob data = Blob.valueOf('Hello');
System.debug(data);

๐Ÿง‘โ€๐Ÿ’ป Demo Class with All Data Types

public class VariableDemoClass {

    public void numericDataTypes() {
        Integer i = 10;
        Long lng = 1234567890L;
        Decimal dcl = 45.67;
        Double dbl = 98.76d;
        System.debug(i);
        System.debug(lng);
        System.debug(dcl);
        System.debug(dbl);
    } 

    public void textDataType() {
        String str = 'Apex Basics';
        System.debug(str);
    }

    public void dateDataType() {
        Date dt = System.today();
        DateTime dtm = DateTime.newInstance(2024, 5, 14, 10, 30, 0);
        Time tm = Time.newInstance(10, 30, 0, 0);
        System.debug(dt);
        System.debug(dtm);
        System.debug(tm);
    }

    public void otherDataType() {
        Id accId = '0015g00000ABCdE';
        Boolean isEnabled = false;
        Blob sampleBlob = Blob.valueOf('Test Data');
        System.debug(accId);
        System.debug(isEnabled);
        System.debug(sampleBlob);
    }
}

โ–ถ๏ธ Execute in Anonymous Window

VariableDemoClass obj = new VariableDemoClass();
obj.numericDataTypes();
obj.textDataType();
obj.dateDataType();
obj.otherDataType();

๐Ÿงฉ Common Naming Styles/Conventions in Code

ConventionExample
PascalCaseThisIsPascalCase
camelCasethisIsCamelCase
snake_casethis_is_snake_case
kebab-casethis-is-kebab-case

๐Ÿง  Types of Variables in Apex

๐Ÿ”น Local Variable

  • Declared inside a method

  • Scope is limited to that method only

  • Not accessible outside the method where it's declared

public class VariableScopeExample {

    public void showMethod1() {
        Integer methodOneValue = 5;
        System.debug('Inside Method 1 : ' + methodOneValue);
    }

    public void showMethod2() {
        Integer methodTwoValue = 10;
        System.debug('Inside Method 2 : ' + methodTwoValue);
    }
}

๐Ÿ›  Execute in Anonymous Window:

VariableScopeExample vsObj = new VariableScopeExample();
vsObj.showMethod1();
vsObj.showMethod2();

๐Ÿ”ธ Global (Instance) Variable

  • Declared outside the methods, but inside the class

  • Accessible across all methods within the class

public class InstanceVariableExample {

    Integer sharedValue = 10;

    public void modifyValue() {
        System.debug('Before Modification: ' + sharedValue);
        sharedValue = 20;
    }

    public void displayValue() {
        System.debug('After Modification: ' + sharedValue);
    }
}

๐Ÿ›  Execute in Anonymous Window:

InstanceVariableExample obj = new InstanceVariableExample();
obj.modifyValue();
obj.displayValue();

๐Ÿง  Knowledge Wrap-Up

  • ๐Ÿ“ Variables are used to temporarily store values.

  • ๐Ÿ“ Local Variables live only within the method they are declared in.

  • ๐Ÿ“ Global (Instance) Variables are shared across methods in a class.

  • ๐Ÿ“ Apex supports multiple primitive data typesโ€”each suited for specific use cases.

  • ๐Ÿ“ Choosing appropriate data types is essential for clarity, performance, and code stability.

0
Subscribe to my newsletter

Read articles from Black BUC directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Black BUC
Black BUC