Arrays

Arrays store multiple values of the same type and have a fixed size.

Example:
int[] nums = {1, 2, 3, 4};

System.out.println(nums[0]); // 1
This accesses the first element of the array using index 0.

Looping through an array:
for(int i = 0; i < nums.length; i++){
System.out.println(nums[i]);
}

For each loop:

for (int n : nums) {

System.out.println(n);

}
This loop goes through every element using the length of the array.

Array methods:

  • array.length — gets the number of elements in the array

  • Accessing an element using arr[i]

  • Changing an element using arr[i] = value

  • Creating an array using new (example: int[] a = new int[length])

  • Creating an array using an initializer list (example: int[] a = {1, 2, 3})