Arrays Lesson
Arrays
Array Syntax
- int [] array = new int[10];
- int [] array2 = {10,9,8,7,6,5,4,3,2,1}; Bound Errors
- when you access an array element that does not exist Traverse an Array
- Any sort of loops - main way to access is for loop
- enhanced for loop: variable element is assigned to values[0]
- specific purpose - get elements of a collection from beg to end
- better to use when the number of elements in the array is unknown
- basic for loop - index varibale loop assigned as 0, 1
- better to use when we knwo the number of iterations
public class Array {
private int[] values = {1, 2, 3, 4, 5, 6, 7, 8};
public void printElements(){
for(int i = 0; i < values.length; i++){
System.out.println(values[i]);
}
}
public void swapElements(){
int lastElement = values[values.length-1];
values[values.length-1] = values[0];
values[0] = lastElement;
}
public void replaceAllZero(){
for(int i = 0; i < values.length; i++){
values[i] = 0;
}
}
public static void main(String[] args){
System.out.println("First and Last Element Swap: ");
Array swapElements = new Array();
swapElements.swapElements();
swapElements.printElements();
System.out.println("Replacing All Elements w/ Zero: ");
Array replaceAllZero = new Array();
swapElements.replaceAllZero();
swapElements.printElements();
}
}
Array.main(null);