Notes

  • Arrays are objects defined by type[] name = new type[size] or initialized with elements using type[] name = new type[]{a,b,c,...}
  • Loops an enhanced can iterate through arrays
  • Index goes from 0 to size-1
  • Algorithms can be used to modify or get info about arrays

Homework

  • Swap the first and last element in the array
  • Replace all even elements with 0
  • Return true if the array is currently sorted in increasing order
  • Return true if the array contains duplicate elements
import java.util.*;
import java.io.*;

public class ArrayMethods {
    private int[] values;
    public ArrayMethods(int[] array) {
        this.values = array;
    }
    public int[] getArray() {
        return this.values;
    }
    public String getString() {
        return Arrays.toString(this.values);
    }
    public void swap() {
        int temp = values[0];
        values[0] = values[values.length - 1];
        values[values.length - 1] = temp;
    }
    public void replaceEven() {
        for (int i = 0; i < values.length; i++) {
            if (values[i] % 2 == 0) {
                values[i] = 0;
            }
        }
    }
    public boolean increasingOrder() {
        for (int i = 0; i < this.values.length - 1; i++) {
            if (values[i] > values[i+1]) {
                return false;
            }
            return true;
        }
        return false;
    }
    public static void main() {
        ArrayMethods method = new ArrayMethods(new int[]{1,2,3,4,5});
        System.out.println(method.getString());
        System.out.println(method.increasingOrder());
        method.swap();
        System.out.println(method.getString());
        method.replaceEven();
        System.out.println(method.getString());
        System.out.println(method.increasingOrder());
    }
}
ArrayMethods.main();
[1, 2, 3, 4, 5]
true
[5, 2, 3, 4, 1]
[5, 0, 3, 0, 1]
false