K-12 CS Teacher Professional Development Workshop
Reading
1D Arrays
Arrays are fundamental data sets in Java. Unlike primitive data and strings, arrays can hold large sets of unique data of the same type. For example, consider this array declaration...
int[] arr = new int[5];
This array is an array of type integer, and it is declared to have a size of five. To populate the array, we can change each element to whatever we want. The first element is marked as arr[0] while the last element is arr[4]. Thus, here is how we would populate the array using the assignment (=) operator.
arr[0] = 0;
arr[1] = 1;
arr[2] = 2;
arr[3] = 3;
arr[4] = 4;
Now we have an array with 5 elements labeled 0-4.
Let's say we wanted to increase the value of all the integers in the array by +1. We could increase each one manually, but that would be lengthy and inefficient. Instead, we could use a for loop to increase all the elements of the array by +1.
for (int i = 0; i < arr.length; i++) {
//arr.length == 5;
arr[i]++;
}
Each element should increase by one after the loop has ran, making arr[0] == 1, arr[1] == 2, etc.
Alternative Declaration Methods (1D Arrays)
There are a couple other ways to declare 1D arrays. If necessary, one could declare the array and all its elements in one line like this...
int[] arr2 = {0, 1, 2, 3, 4};
Or you could initialize your array and declare it later in the program...
int[] arr;
arr = new int[5];
2D Arrays
2D Arrays add another dimension to regular arrays. You can think of these arrays as squares. Their declaration looks like this...
int[][] arr = new int[5][5];
Think of these arrays from the top left to the top right and top-down (an initial declaration of any integer will automatically assign it to 0).
Here is how one would loop and print the array to look exactly as shown above...
for (int i = 0; i < arr.length; i++) {
//This first array loops each first element of a row and progressively goes downwards.
for (int j = 0; j < arr[i].length; j++) {
//This second array goes across the rows to print.
System.out.print(arr[i][j]);
}
System.out.println();
//This creates the "enter" after each row is printed.
}
Alternative Declaration Methods (2D Arrays)
int[][] arr = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0},
{0, 1},
{0, 0, 1}
};
This is a method of declaring an array which allows you to freely manipulate the length of each row. An array which has multiple rows of varying lengths is called a "jagged array".