Created: 2023-08-27 20:04
Status: #concept
Subject: Programming
Tags: Java Java Data Type java.util.ArrayList java.util.Arrays C Array

Java Array

We can create type[] arrays of primitive Java Data Types with a static size.

  • it is a Reference Type, so it is an Object that is passed by address to Methods.

Syntax

int[] numbers = new int[3]; // an array with 3 indices
String[] strings = new String[5]; // can also use the String type

// Initialization during declaration
float[] floats = {4.20, 6.9, 7.77};
System.out.println(floats.length); // 3

// ArrayList<T>.get(int index)
System.out.println("1st in strings array: " + strings[0]);

// ArrayList<T>.size()
System.out.println("Size of strings array: " + strings.length); // not a method

Multidimensional Arrays

We can imitate C Multidimensional Arrays with Java by specifying the array's new type[rows][cols].

  • to get the rows, we can do array.length.
  • to get the cols of a row, we can do array[0].length, "get the number of elements in the first row of the array".

int rows = 2;
int columns = 3;
int[][] twoDimensionalArray = new int[rows][columns];

System.out.println("row, column, value");
for (int row = 0; row < twoDimensionalArray.length; row++) {
    for (int column = 0; column < twoDimensionalArray[row].length; column++) {
        int value = twoDimensionalArray[row][column];
        System.out.println("" + row + ", " + column + ", " + value);
    }
}

We can also let the compiler implicitly determine the size with an initialization.

int[][] matrix = {
    {3, 2, 7, 6},
    {2, 4, 1, 0},
    {3, 2, 1, 0}
};
We can make Ragged Arrays by having variable length rows.

  • Each array in the matrix[N] will have its own .length property.

int[][] matrix = {
    {1},
    {2, 2},
    {3, 3, 3},
    {4, 4, 4, 4}
};

Traversing a size-independent multidimensional array looks like this:

public static String arrayAsString(int[][] array) {
    StringBuilder output = new StringBuilder();

    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            output.append(array[i][j]);
        }
        output.append("\n");
    }

    return output.toString();
}

Utility Methods

See java.util.Arrays for useful static methods like .sort(array) and .equals(array1, array2).

References