Declaring Arrays

Two types, arrays and ArrayLists Primitive data types contain a single var type (int, charm float) Referenced (string array classes)

Array Syntax

int[] array = new int[10];

Common Errors

values has 10 elements but the index can only range from 0 to 9 Work like objects so must initialize

Traverse an Array

Main way is For loops where you go through each element of the array (enhanced or basic) Basic For loop is For when you know number of elements

Homework

Write a class called ArrayMethods that contains two methods that utilize/manipulate an array. You may choose 2 of the 4 options below to complete. Extra credit for doing all 4 options. Make sure to show test cases for all of the options you choose.

public class ArrayMethods {
    private int[] values = {0, 1, 2, 3};

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

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

    public void evenToZero(){
        for(int i = 0; i < values.length; i++){
            if (values[i] % 2 == 0){
                values[i] = 0;
            }
        }
    }

    public static void main(String[] args){
        
        System.out.println("First and Last Element Swap: ");
        ArrayMethods swapElements = new ArrayMethods();
        swapElements.swapElements();
        swapElements.printElements();

        System.out.println("Replacing All Elements w/ Zero: ");
        ArrayMethods evenToZero = new ArrayMethods();
        swapElements.evenToZero();
        swapElements.printElements();
    }
}
ArrayMethods.main(null);
First and Last Element Swap: 
3
1
2
0
Replacing All Elements w/ Zero: 
3
1
0
0