3 / 16

Variables

We use variables to store data.
A variable has a name and a type.
We will write name: Type here, for example amount: Integer.


Let's say we are calculating the total amount we spent on some items.
We can use 3 variables:

  • amount: Integer
  • price: Real
  • total: Real

Before we use a variable, we must declare it.
Click the line and select Declare (Declare).
Then:

  • select the added Declare block
  • enter amount for variable name
  • select Integer for its type
  • enter 3 for its initial value

Do the same for price, set its type to Real and value to 1.5.

Declare total, set its type to Real and value to amount * price.

Lastly, add an Output block to print the value of total (total).

When you run the program you should see number 4.5 printed.


As you can see, you can use variable name to refer to its value. Instead of repeating 3 in the program every time it is used, we just use amount.

 
id_269096a9_c328_4356_9a7f_7120477af1c3 Begin id_3e7daeb3_a2d9_4734_970d_d0cc376b64eb End id_269096a9_c328_4356_9a7f_7120477af1c3:s->id_3e7daeb3_a2d9_4734_970d_d0cc376b64eb:n
public class NewProgram {

  public static void main(String args[]) {
  }
}