Title here
Summary here
In Java, an array is a numbered sequence of elements of a specific length. In typical Java code, arrays are extremely common and are useful in various scenarios.
public class ArrayExample {
public static void main(String[] args) {
// Here we create an array `a` that will hold exactly 5 `int`s.
// The type of elements and length are both part of the array’s type.
int[] a = new int[5];
System.out.println("emp: " + 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: " + Arrays.toString(a));
System.out.println("get: " + a[4]);
// The `.length` attribute returns the length 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: " + Arrays.toString(b));
// You can also have the compiler count the number of elements for you with `new int[]`.
b = new int[]{1, 2, 3, 4, 5};
System.out.println("dcl: " + Arrays.toString(b));
// If you specify the index with `:`, the elements in between will be zeroed.
b = new int[]{100, 0, 0, 400, 500};
System.out.println("idx: " + Arrays.toString(b));
// Array types are one-dimensional, but you can compose types to build multi-dimensional data structures.
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: " + Arrays.deepToString(twoD));
// You can create and initialize multi-dimensional arrays at once too.
twoD = new int[][]{
{1, 2, 3},
{1, 2, 3}
};
System.out.println("2d: " + Arrays.deepToString(twoD));
}
}
Note that arrays appear in the form [v1, v2, v3, ...]
when printed with Arrays.toString
.
$ javac ArrayExample.java
$ java ArrayExample
emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]
Next example: Slices.