Arrays

Fixed-size lists of one type, plus sorting and 2D arrays.

An array has a fixed length that is set when it is created. Indexes start at 0, and going past the end throws ArrayIndexOutOfBoundsException.

Java
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] marks = {72, 95, 60, 88};
    int total = 0;
    for (int m : marks) {
      total += m;
    }
    System.out.println(total / (double) marks.length);

    Arrays.sort(marks);
    System.out.println(Arrays.toString(marks));
  }
}
Output
78.75
[60, 72, 88, 95]

2D arrays

Java
public class Main {
  public static void main(String[] args) {
    int[][] grid = {{1, 2}, {3, 4}};
    System.out.println(grid[1][0]);
    System.out.println(grid.length + " rows, " + grid[0].length + " columns");
  }
}
Output
3
2 rows, 2 columns
โ† Conditions and loopsMethods โ†’