This reference is for Processing 3.0+. If you have a previous version, use the reference included with your software in the Help menu. If you see any errors or have suggestions, please let us know. If you prefer a more technical reference, visit the Processing Core Javadoc and Libraries Javadoc.

Name

Array

Examples
int[] numbers = new int[3];
numbers[0] = 90;  // Assign value to first element in the array
numbers[1] = 150; // Assign value to second element in the array
numbers[2] = 30;  // Assign value to third element in the array
int a = numbers[0] + numbers[1]; // Sets variable 'a' to 240
int b = numbers[1] + numbers[2]; // Sets variable 'b' to 180 

int[] numbers = { 90, 150, 30 };  // Alternate syntax
int a = numbers[0] + numbers[1];  // Sets variable 'a' to 240
int b = numbers[1] + numbers[2];  // Sets variable 'b' to 180

int degrees = 360;
float[] cos_vals = new float[degrees];
// Use a for() loop to quickly iterate
// through all values in an array.
for (int i=0; i < degrees; i++) {         
  cos_vals[i] = cos(TWO_PI/degrees * i);
}

float[] randoms = new float[100];
for (int i = 0; i < randoms.length; i++) {
  randoms[i] = random(100);
}

// You can also use an enhanced loop
// to access the elements of an array
for (float val : randoms) {
  println(val);
}

// This works with arrays of objects, too,
// but not when first making the array
PVector[] vectors = new PVector[5];
for (int i = 0; i < vectors.length; i++) {
  vectors[i] = new PVector();
}

// The syntax only applies when iterating
// over an existing array 
for (PVector v : vectors) {
  point(v.x, v.y);
}
Description An array is a list of data. It is possible to have an array of any type of data. Each piece of data in an array is identified by an index number representing its position in the array. The first element in the array is [0], the second element is [1], and so on. Arrays are similar to objects, so they must be created with the keyword new.

Each array has a variable length, which is an integer value for the total number of elements in the array. Note that since index numbering begins at zero (not 1), the last value in an array with a length of 5 should be referenced as array[4] (that is, the length minus 1), not array[5], which would trigger an error.

Another common source of confusion is the difference between using length to get the size of an array and length() to get the size of a String. Notice the presence of parentheses when working with Strings. (array.length is a variable, while String.length() is a method specific to the String class.)
Syntax
datatype[] var
var[element] = value
var.length
Parameters
datatype any primitive or compound datatype, including user-defined classes
var any valid variable name
element int: must not exceed the length of the array minus 1
value data to assign to the array element; must be the same datatype as the array
Updated on January 1, 2021 03:38:12am EST