Java Arrays
An array is a fixed-size, ordered collection of elements of the same type. Arrays in Java are objects, and their length is fixed once created; it's accessed via the .length field (not a method).
Arrays can be one-dimensional or multi-dimensional, allowing you to model grids and tables of data.
int[] arr = new int[5];
int[] arr2 = {1, 2, 3};
arr[0] = 10;Declaring and accessing arrays
Arrays are declared with `type[] name = new type[size];` or with an array literal `{1, 2, 3}`. Elements are accessed with zero-based indices.
Multi-dimensional arrays
A 2D array like `int[][] grid` is an array of arrays, useful for representing tables, matrices, or grids.
public class Main {
public static void main(String[] args) {
int[] nums = {10, 20, 30};
System.out.println(nums[1]);
System.out.println(nums.length);
nums[0] = 99;
System.out.println(nums[0]);
}
}20
3
99Elements are accessed by index, length gives the array size, and elements can be reassigned.
Key points
- Arrays have a fixed size once created.
- Indices start at 0.
- length is a field, not a method, on arrays.
- 2D arrays are arrays of arrays.
