Strings As Our First Variable
Developers use variables to save and store information that they want to access and reuse in the future. Learn how to create different kinds of variables and see how they can make your life easier as your code gets more complex. In this video we will work with our first Data Type: the 'String'.
Time to explore the procedure for creating variables and using it in a program. We will first deal with strings before going to numbers. Assigning a string to a variable requires the variable to be declared first along with the data type. We declare a variable like this:
var longAssedStr: String;
Here we can see that the keyword "var" is required to declare any variable. "longAssedStr" is the variable, and the part following the colon shows what type of data this variable is. For strings, would you believe the data type is "String"?? Sure enough it is, so we type the colon followed by "String." The variable declaration must always end with a semi colon as shown.
After declaring a variable, we must assign a string to it if we want to use it later. This can be done in the same line where the variable is declared, in the next line, or elsewhere in the code. We will discuss the first two methods in this section.
Firstly, most developers prefer to declare and assign a variable in a single line: saves space and is more readable. For this we type:
var yoMamaStr: String = "wears army boots";
Here we can see that the semi colon is moved to the end of the line of code, after the string and the variable is set to equal some string within double quotes. Finally, the line must end with a semicolon. In this way the variable is declared and assigned within the same line.
There is another process where we declare the variable in one line and assign data to it in another line. For this we first declare the variable as we said earlier, along with the semicolon. In the next line we type
yoMamaStr = "wears army boots";
The result is same but two lines are used here instead of one. Remember that even the second line must be ended using a semi colon: every line of code you write must end in that semicolon! These little things are very important to remember because they can cause errors during compilation. Nasty errors.
After declaring and assigning a variable using either method, next we see how to use it in the program later. This is very simple and we just need to type the variable in the trace function to print the actual data. It looks like this:
trace(yoMamaStr);
Unlike numbers, a string is the only text data written in double quotes, so it cannot be subjected to any modifications.
Ready to Level Up Your Skills?
Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!
Enroll Now for Free!