September 25, 2016 by LanceShi
2.1 Using variables to store information
There are always things we want to remember. We need to remember which tasks we need to work on. We need to keep track of grocery list we want to buy at the shopping centre. In those cases, if the information is hard for our brain to remember all of them, we write them down in a piece of page or track them down in the computer. So later we can find them.
Variables serve for this purpose in programming. It stores the data in a variable and later on we can reuse it. It gives the variable a variable name so later on we know how to retrieve it. Below is an example:
String greetings = 'Hello, '; String myName = 'Lance'; //Replace it with your name System.debug(greetings + myName); greetings = 'Bonjour, '; System.debug(greetings + myName);
Execute this code in your developer console. Your result should be similar to this:
A bit explanation
The grammar for defining and reusing variables is not hard in Apex. You need to specify the variable type, followed by the variable name. Then you can initialize the value of it. The initialization is not mandatory. But if you don’t initialize it, it will default to null, which means no value.
Apex is a strong type language, which means you have to specify a type to the variable. Here both variables’ type are String, which means a text variable. We will talk more about variable types in next post.
Followed is your variable’s name. Your variable name has to be unique. You can pretty much name your variable anything you want, as long as it is in one word. And make sure it doesn’t conflict with Apex reserved keywords.
Then you can initialize the value of your variable by using =.
You can change your variable’s value at any time later in your programme. And you can reuse it as many times as you want. But you can’t change your variable’s type. So,
String greetings = 'Hello'; //greetings = 123; //The above line won't work because you can't assign an integer value into a String variable.
You can’t assign some value of a different kind to a variable later on. As the above code shows.
Create two variables: firstName and lastName to hold your first and last name. Then display in debug log this sentence using both variables:
Hello, [Your Name]. Welcome to the world of Apex programming.