Codecademy Logo

Arrays in Java

Print Cheatsheet

Arrays

An array is a collection of values with the same data type.

String[] animals = {"Giraffe", "Elephant", "Toucan"};
// Access an element via its index:
System.out.println(animals[0]); // Prints: Giraffe
// Change an element value:
animals[1] = "Lion";
// Find number of elements in an array:
System.out.println(animals.length); // Prints: 3
// Traverse array using for loop:
for (int i = 0; i < animals.length; i++) {
System.out.println(animals[i]);
}
/* Prints:
Giraffe
Lion
Toucan
*/
// Traverse array using for-each loop
for (int i: animals) {
System.out.println(i);
}
/* Prints:
Giraffe
Lion
Toucan
*/

2D Arrays

A 2D array is an array that stores arrays of the same data type.

// Declare a 2D array that stores char arrays
char[][] letters = {{'A', 'a'}, {'B', 'x'}, {'C', 'c'}};
// Access an element via its index:
System.out.println(letters[0][1]); // Prints: a
// Change an element by accessing its index:
letters[1][1] = "b";
// Iterate over 2D array in row-major order:
for (int i = 0; i < letters.length; i++){
for (int j = 0; j < letters[0].length; j++){
System.out.print(letters[i][j]);
}
}
// Prints: AaBbCc
// Iterate over 2D array in column-major order:
for (int i = 0; i < letters[0].length; i++){
for (int j = 0; j < letters.length; j++){
System.out.print(letters[j][i]);
}
}
// Prints: ABCabc