Using Arrays:
- Arrays can hold
multiple values of the same data type
- They are objects, but they hold either primitive types or reference types
- Arrays in Java start at index 0
int [] x = new int [4];
int [] y = {3, 5, 7, 2};
x[2] = 12;
//y[4] = 21; out of bounds error
System.out.println(y[3]);
for (int i = 0; i < x.length; i++){
System.out.println(x[i]);
}
public class Array2 {
public static void main(String[] args){
int a = 3;
int b = a;
b = 100;
int [] c = {1, 2, 3, 4}; //pointed is located in stack, but the data of the array is located in the heap!!
int [] d = c; //same objects on the heap because d is set equal to c
d[1] = 99; //affects both objects
d = new int[5];
int [] e = {5, 6, 7, 8};
int [] f = {5, 6, 7, 8}; //separate objects on the heap!!
f[1] = 99;
}
}
Array2.main(null)
Traversing an Array:
- Arrays in Java start at 0
- .length will return the number of indexes in an array
- traverse an array with a For Loop or a For-Each Loop
int[] x = {2, 1, 5, 8};
for (int i = 0; i < x.length; i += 2){
System.out.print(x[i] + " ");
}
// enhanced for loop, for each loop
//can't skip indexes
//can't modify data within array
for (int t : x){
System.out.print(t + " ");
}
int sum = 0;
for (int i = 0; i < x.length; i++){
x[i] *= 2;
sum += x[i];
}
System.out.println(sum);
Reversing an array:
- can be reversed by swapping values of the first half and the second half
- values can also be swapped by copying values to the opposite index in a temporary array
public class Array {
public static void main(String[] args) {
int[] x = {4, 2, 6, 1, 7};
// Reverse the array
for (int i = 0; i < x.length / 2; i++) {
int temp = x[i]; //temp is set = 4
x[i] = x[x.length - i - 1]; // 4 is set equal to (5-0-1 = 4), which is 7
x[x.length - i - 1] = temp; //index 4 is set = 4
}
// Print the reversed array
for (int i = 0; i < x.length; i++) {
System.out.println(x[i]);
}
}
}
Array.main(null);
Find the Largest Number in an Array:
public class FindLargest {
public static void main(String[] args) {
int[] anArray = {-2, 1, 6, -3, 10, 8};
int largest = anArray[0];
for (int i = 0; i < anArray.length; i++){
if (largest < anArray[i]){
largest = anArray[i];
}
}
System.out.println(largest);
}
}
FindLargest.main(null);
public class Example {
public int highestNumber(int[] numbers){//part a
int highestNumber = 0;
for (int i = 0; i < numbers.length; i++){
if (numbers[i] > highestNumber){
highestNumber = numbers[i];
}
}
return highestNumber;
}
public double averageNumber(double[] numbers){//part b
double sum = 0;
double totalNumbers = 0;
for (int i = 0; i < numbers.length; i++){
sum += numbers[i];
totalNumbers += 1;
}
return sum/totalNumbers;
}
public static void main(String[] args){
int[] numbers = {1, 3, 4, 7, 2};
double[] numbers2 = {1, 3, 4, 7, 2};
Example newClass = new Example();
System.out.println(newClass.highestNumber(numbers));
System.out.println(newClass.averageNumber(numbers2));
}
}
Example.main(null);