Syntax help with 2D array

Just to clarify your code

byte[][] chord_Bank2;

declares a variable called chord_Bank2 but does not define its contents. At this stage the variable chord_Bank2 has the value null

static final byte[][] CHORD_BANK2 = {
  { 40, 45, 50, 55, 59, 64 }, // open strings 0

This statement not only declares a 2D byte array it also defines the array contents.

Note both these statements are executed before the setup method is called.

chord_Bank2 = new byte[5][7];

This statements defines the contents of a previously declared array. Since the array elements are of type byte (a Java primitive data type) then all the elements take on the default value of zero which is why you got 0’s printed out.

You could change the statement to

chord_Bank2 = CHORD_BANK2;

and it would use the values in CHORD_BANK2.

One word of warning, using the final keyword with CHORD_BANK2 will prevent later statements like

CHORD_BANK2 = new byte[5][7];

being compiled but it does not prevent changes to values stored inside the array. In these statements

chord_Bank2 = CHORD_BANK2; // both reference the SAME array
chord_Bank2[2][3] = 999; // will also change the value in `CHORD_BANK2`

After these statements are executed

println(CHORD_BANK2[2][3]); 

will display 999

3 Likes