Variables

Variables are containers for data. Essentially a variable is something that can hold a value and that value can be changed (They can vary).

Data Types:
Variables in Processing (and other strictly typed languages) must be defined or declared with their type.

The different (primitive) types that Processing/Java support are as follows:
int – An integer. Whole numbers only.

int someint = 5;

boolean – True or False. Often the result of an expression.

boolean somebool = true;

float – A number with a decimal point. 1.5, 3.987 and so on.

float somefloat = 99.76;

byte – An 8 bit value. Ranges from -127 to 128 in value.

byte mybyte = -90;

char – A single character.

char mychar = 'A';

Declaration:
Variables must be declared with their type as shown (in the examples above as well as) here:

int myinteger;
float yourfloat;
boolean mybool;

Assignement:
Once they are declared, you are free to assign values to them and subsequently use them in operations:

myinteger = 5;
myinteger = 5 + 5;
myinteger = myinteger - 5;
yourfloat = 5.5;

Of course, as shown in the examples above, you can take a shortcut and do both declaration and assignement in one step:

int someint = 89; 

VARIABLE SCOPE

You may have noticed the integer is declared outside of the setup() method we wrote here. This is due to something called variable scope. The concept is that variables are only accessible to the block of code they are defined in.

For instance, if we declared a variable in the setup function, we would not be able to access that variable in the draw function.

Blocks of code are defined by “{” and “}”. Any code that is within the brackets is considered in the same block. Therefore, setup and draw have their own blocks of code.

A code block:
        {
            // Some code
            // Some more code
        }

If you declare a variable outside of a block of code, in the main processing code section it is a global variable. If you declare it inside of a block of code, it is a local variable. Local to that block.

A global and a local variable:

        int myint = 90;  // Global
        
        void setup()
        {
            int myotherint = 100; // Local to the setup function
        }