Arrays in Minitab

In Java, an array is a fixed-size collection of elements of the same type. Arrays are useful in many scenarios, but in typical Java code, ArrayList or other collections from the java.util package are more common for dynamic sizing.

public class Arrays {
    public static void main(String[] args) {
        // Here we create an array 'a' that will hold exactly 5 integers.
        // By default, an array is filled with zeros for numeric types.
        int[] a = new int[5];
        System.out.println("emp: " + java.util.Arrays.toString(a));

        // We can set a value at an index using the array[index] = value syntax,
        // and get a value with array[index].
        a[4] = 100;
        System.out.println("set: " + java.util.Arrays.toString(a));
        System.out.println("get: " + a[4]);

        // The length property returns the size of an array.
        System.out.println("len: " + a.length);

        // Use this syntax to declare and initialize an array in one line.
        int[] b = {1, 2, 3, 4, 5};
        System.out.println("dcl: " + java.util.Arrays.toString(b));

        // Java doesn't have a direct equivalent to Go's "..." syntax for array initialization.
        // The closest would be to use the array initializer syntax as shown above.

        // Java doesn't have a direct equivalent to Go's index-based initialization.
        // You would need to initialize the array and then set specific elements.
        int[] c = new int[5];
        c[0] = 100;
        c[3] = 400;
        c[4] = 500;
        System.out.println("idx: " + java.util.Arrays.toString(c));

        // Array types are one-dimensional, but you can create multi-dimensional arrays.
        int[][] twoD = new int[2][3];
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 3; j++) {
                twoD[i][j] = i + j;
            }
        }
        System.out.println("2d: " + java.util.Arrays.deepToString(twoD));

        // You can create and initialize multi-dimensional arrays at once too.
        int[][] twoD2 = {
            {1, 2, 3},
            {4, 5, 6}
        };
        System.out.println("2d: " + java.util.Arrays.deepToString(twoD2));
    }
}

Note that arrays are printed using Arrays.toString() for one-dimensional arrays and Arrays.deepToString() for multi-dimensional arrays in Java.

When you run this program, you’ll see output similar to this:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

Java arrays are similar to those in many other languages, providing a way to store multiple elements of the same type in a contiguous block of memory. They offer constant-time access to elements by index but have a fixed size once created.