A variable is a placeholder for a value. Variables are also stored in the programming for a memory location that is filled with a value. Variables need to be defined with a data-type, to define its storage space requirements. The name of the variable must start with a letter, but can it may contain numbers in the word. In processing, variable names are case-sensitive.
Variables also have a lifetime. The computer manages the storage of variables, and when the life span is over, the memory is released again (Garbage-Collector). The range (Scope) in which a variable is accessible or active is defined by brackets ({}) (see also classes and functions). Variables that are at the top level are called global variables as they are accessible all over the program. Variables declared within brackets are local variables. If a local variable has the same name as a global variable, the local variable overrides it within its scope.
// variable Declaration int x1 = 15; // an integer i.e a whole number float valF = 0.323; // a floating point number i.e a numbers with a decimal point boolean bFlag = false; // a true or false value i.e a single bit value String message = "hallo 1"; // a collection of characters char character = 'g'; // a sigle character. Note the different quotation marks String msg1 = new String("hallo 2"); println(x1); println(valF); println(bFlag); println(message); println(character); println(msg1);
We can also makes copies or combine variables.
int x1 = 10; int x2 = 5; println(x1); println(x2); int x3 = x1 + x2; // 15 x2 = x3 - x1; // 5 println(x3); println(x2);
Example
Almost the same as the first exercise, but now with variables.
int length1 = 150; int length2 = 200; size(300,300); // define window size background(0); // define background colour stroke(255,255,255); // define line colour line(100,10,100,length1); // draw a line line(150,10,150,length2); line(200,10,200,250); fill(0,0,0); // fill colour strokeWeight(5); // line thickness ellipse(100,length1,50,50); // draw an ellipse ellipse(150,length2,50,50); // draw an ellipse noFill(); // turn off fill ellipse(200,250,50,50); // draw an ellipse