Declare variables and perform operations according to the following conditions
- Declare a variable a of type Integer and assign 10 to it.
- Declare a variable b of type Integer and assign 20 to it.
- Add a and b together and assign the result to the Integer variable sum.
- Finally, output the value of sum to the console using System.debug().
Solution Example
// Declare a variable a of type Integer and assign 10
Integer a = 10;.
// Declare variable b of type Integer and assign 20
Integer b = 20;
// Add a and b together and assign the result to variable sum of type Integer
Integer sum = a + b;
// Output the value of sum to the console using System.debug()
System.debug('Sum of a and b: ' + sum);
Explanation
1. Declaring Variables
First, let us explain what a “variable” is.
A variable is like a “box” used to temporarily store data in a program. In this example, we will prepare a “box” to store numbers.
Declare a variable a of type Integer and assign 10
Integer a = 10;
- Integer means “type” for integers, and in Apex, when you create a variable, you need to specify what kind of data (type) you want to handle.
- a is the name of the “box”. You can choose this name yourself, but in this case I chose a.
- = does not mean “equal,” but means to put (assign) the value written on the right side into the box on the left.
- 10 is the number to put into the variable a.
Declare a variable b of type Integer and assign 20
Integer b = 20;
As with a above, now put the number 20 into the variable named b.
2. Adding Variables a and b
Next, add a and b together and put the result into another variable sum.
Integer sum = a + b;
- a + b adds the numbers in a (10) and b (20).
- The result of the addition is 30, so the result is put into a variable named sum.
3. Displaying the result on the console
Finally, the result of the addition (sum) is output to a place called the console.
System.debug('Sum of a and b: ' + sum);
- System.debug() is a useful tool for checking the contents of variables in the middle of a program and for debugging.
- ‘Sum of a and b: ‘ is part of the message, meaning “The sum of a and b is”. This string is attached to the value (30) contained in the sum and output.
Result displayed in the console
When you actually run this program, you will see the following message.
Sum of a and b: 30
This indicates that 30 was correctly calculated as a result of adding a and b together.
Summary of the entire process
- We created a box called “variable” with a and b to store numbers.
- We put 10 in a and 20 in b.
- We added them together and put the result in a new box called sum.
- System.debug() was used to display the result (the contents of sum) on the console.
This is the entire flow of the code.