Unit 6 Arrays
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
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);