Apex Variables
Introduction to Variables in Apex:
Variables in Apex are containers used to store data values.
Each variable has:
A data type → defines what kind of data it can hold (like text, number, true/false).
A name (identifier) → helps us refer to that variable later in the code.
Apex is a statically typed language, meaning the data type must be declared before using the variable.
1. Declaring Variables
Variables in Apex are declared using the following syntax:
apex
Integer age;
Here:
• Integer is the data type
• age is the variable name (identifier)
This means: You’ve created a variable (a box) that can store whole numbers.
2. Declaring a Variable and Assigning a Value
Scenario 1: Declare First, Then Assign Value
apex
// Step 1: Declare an integer variable named ‘age’. It is currently uninitialized.
Integer age;
// Step 2: Assign the value 25 to the variable ‘age’.
age = 25;
Explanation:
First, we created the variable age to store a whole number.
Then, we assigned it the value 25.
Scenario 2: Declare and Initialize in One Step
apex
// Declare an integer variable named ‘age’ and initialize it with the value 20.
Integer age = 20;
Explanation:
We declared the variable age and immediately gave it the value 20.
Concept | Apex Example |
---|---|
Declare Variable | Integer age; |
Assign Value | age = 25; |
Declare & Assign | Integer age = 20; |