Skip to main content

Variable in Apex

Published 4 min readMarkdown
Part of seriesApex Basics

🔍 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.

No comments yet. Be the first to comment.

More from this blog