Arrays

  • contains a collection of data
  • can be primitive or referenced
  • element - one value in an array
  • index - the position of one value in an array
  • use loop to access array
    • enhanced for loop - use when number of elements in array unknown
    • basic for loop - use with known number of elements

Homework

public class Array {
    private int[] values = {0, 2, 4, 6, 8, 10};

    public void printValues(){
        for(int i = 0; i < values.length; i++){
            System.out.println(values[i]);
        }
    }

    public void swapValues(){
        int lastElement = values[values.length-1];
        values[values.length-1] = values[0];
        values[0] = lastElement;
    }

    public void replaceZero(){
        for(int i = 0; i < values.length; i++){
            values[i] = 0;
        }
    }

    public static void main(String[] args){
        
        System.out.println("Swapping first and last: ");
        Array swapValues = new Array();
        swapValues.swapValues();
        swapValues.printValues();

        System.out.println("Replace all with zero: ");
        Array replaceZero = new Array();
        swapValues.replaceZero();
        swapValues.printValues();
    }
}

Array.main(null);
Swapping first and last: 
10
2
4
6
8
0
Replace all with zero: 
0
0
0
0
0
0