B4A FOR BEGINNERS - VARIABLES

Variables hold data (store) in computers memory for easy accessibility. Just as in algebra where you will have an equation like x + 2 = 4  where x represents a figure, so as in programming, there are ways to temporarily assign/store data into variable and access it anytime.

Now lets go back to b4a. Before you can assign a data to a variable, you need to declare the variable and type of data it will hold. The syntax for declaring a variable is as follows:

Dim num1 As Int

Dim keyword is used to let the system know that you are declaring a variable.
num1 is your variable name
As Int is the data type, there are other data types but  in the above example, Int shows the variable will be accepting Integers. You can declare a variable and assign a data to it at the same line as in the example below

Dim num1 As Int = 32  

In other words, you can declare the variable first and then call the variable and assign a data to it.

Dim num2 As Int 

num2 = 145

 Some Common Data types are:
Strings - Holds Text Data
Double - Holds Decimals
Int - Holds Integers
Bolean - Holds True or False

LETS CREATE A PROJECT AND NAME IT VARIABLE
B4A VARIABLES


  1. Under sub Globals create two variables namely x, y , answer all as Int
  2. Open the designer and add a label to the layout. Leave the default name as label1, right click and generate member and save the whole layout as main. Remember to load the layout in the main project.
    B4A DESIGNER
  3. Assign data to the variables x  = 5, and y = 7
  4. Variable answer = x + y (Note: Because we assigned 5 to x, and 7 to y, even if we call just x and y, the representation is 5 and the 7. In this case we are adding 5 to 7)
  5. Now assign the answer to label1 like this (label1.text = answer).
  6. Now run your program,
  7. The answer you are suppose to get should be 12 (5 + 7)

Labels: , , , , , ,