What are variables in apex?
In apex, a variable is like a container used to store information that can change while the program runs. This information could be a number, text, date, or even a more complex data type like a customer record.
The type of a variable determines the kind of data that can be assigned to it. For example, numbers can be assigned to an Integer variable, while addresses can be assigned to a String variable, and so on.
Following is the syntax of declaring an integer variable with a default value of 10
Integer count = 10;
In the above example:
- The keyword
Integer
is used to declare an integer variable. - The
count
is the name of the integer variable. - The value
10
is assigned to the integer variablecount
.
Important
Always follow the correct syntax while writing code to avoid compilation errors.
Why to use variables
Store Data
Variables act as containers to store information like Name, Age, or Sales. Think of them as labeled boxes where you can put different types of data.
String name = 'John';
Integer age = 25;
Decimal totalSales = 3000;
Example
name: John,age: 25,totalSales: 3000
Make Programs Dynamic
Variables enable programs to adapt based on user input, creating personalized experiences. Instead of hard-coding values, your app can respond to different users.
String userName = 'Sarah';
String greeting = 'Welcome, ' + userName + '!';
Example
Welcome, Sarah!
(The name Sarah changes based on the logged-in user)
Perform Calculations and Logic
Variables allow you to perform calculations and make decisions using logical conditions. This is where variables truly shine in programming.
Decimal price = 10;
Integer quantity = 5;
Decimal total = price * quantity; // total = 50
Example
total = price * quantity
$50 = $10 * 5