Notes:

  • An array is a type of data structure that contains collections of data.
  • The data in an array can be primitive or referenced.
  • The parts of an array comprise of elements and indices. An element is a singular value in an array, while an index is the position of a value in the array. Java uses 0-based indexing, meaning the first value of an array is at index 0.
  • Method 1 of initializing arrays: int[] array = new int[10]; This declares an array with 10 elements with int type.
  • Method 2 of initializing arrays: int[] array = {1, 2, 3, 4}; This specifies the initial values of an array.
  • To traverse through an array, any sort of iteration, specifically basic for loops and enhanced for loops, should be used.
  • The array.length method returns the length of an array, or in other words the number of values in an array. The array[i] method returns the element of an array at index i.

Homework:

  • Swap the first and last element in the array
  • Replace all even elements with 0
// Import Java Arrays library
import java.util.Arrays;

public class ArrayMethods {
    // Initialized array with private modifiers
    private int[] values = {1, 4, 3, 5, 6, 8, 7};

    // Swap method for reversing the entire array
    public int[] swap() {
        int[] valuesSwap = values.clone();
        for (int i = 0; i < valuesSwap.length/2; i++) {
            // Store the ith value of the array in a temp variable
            int temp = valuesSwap[i];
            int lastIndex = valuesSwap.length - (i + 1);
            valuesSwap[i] = valuesSwap[lastIndex];
            valuesSwap[lastIndex] = temp;
        }
        return valuesSwap;
    }

    // Replace method for replacing all even numbers in the array with 0
    public int[] replace() {
        int[] valuesReplace = values.clone();
        for (int a = 0; a < valuesReplace.length; a++) {
            // If % produces a remainder of 0, the element is even
            if (valuesReplace[a] % 2 == 0) {
                valuesReplace[a] = 0;
            }
        }
        return valuesReplace;
    }

    // Running method for visualizing outputs
    public static void main(String[] args) {
        ArrayMethods myObj = new ArrayMethods();
        for (int num : myObj.swap()) {
            System.out.print(num + " ");
        }
        System.out.println("");
        for (int num : myObj.replace()) {
            System.out.print(num + " ");
        }
    }
}

ArrayMethods.main(null);
7 8 6 5 3 4 1 
1 0 3 5 0 0 7